dimanche 10 février 2019

How to redesign an instance where common functionality (in a parent class) warrants returning instances of the children?

As per the title, I know this is inherently terrible design, as a parent should know nothing about its children. However, I am in the scenario where

1) All children have reusable behaviour that could be derived from the parent class, 
2) Those reusable methods that ALL subclasses need, warrant returning instances of the current sub classes!

I need all child classes to have the repeatable behaviour but also have the parent class capable of returning instances of the children, this will need a complete refactor, but how do I design it properly?

I have tried using composition instead here, the only problem being that all classes will have to have to declare an explicit public api for using the common functionality and each and every subclass in the future will need to declare it...

class BasePage(object):
    # Some Very Common Behaviour goes here.
    # Nothing product specific, just selenium specific 

class ProductBasePage(BasePage):
    # Reusable behaviour here for the product
    # Some of this behaviour in the parent does web-app navigation which merits (quite rightly) to return instances of children pages, for example (CustomersPage, DashboardPage, ProductsPage) but this is clearly flawed and inheritance is not the answer? but how do I keep the functionality that all subclasses need without then declaring it explicitly in every one of them?

class CustomersPage(ProductBasePage):
    # Customer specific behaviour
    # Should have access the common functionality implicitly from the parent

Customer Page and all other pages which extend the product page should have the ability to use a lot of common functionality that all of the subclasses of ProductBasePage should have, without having each and every subclass to define that behaviour explicitly. The re-usable methods however, return instances of ProductBasePages sub classes as their actions warrant this behaviour...

So how do I achieve this? I think Inheritance is not the answer here, but then how do I get reusability of the common functionality without declaring it explicitly in every class?

The solution to this problem should avoid circular python import dependencies as well.

Thanks

Aucun commentaire:

Enregistrer un commentaire