Question

I have a set of classes that inherit functionality, depending on what they do. They are screen elements:

Some examples would be:
ScreenElement_Text_Area extends ScreenElement_Text extends ScreenElement ScreenElement_Text_Text extends ScreenElement_Text extends ScreenElement ScreenElement_Date_ddmmyyyyhhmm extends ScreenElement_Date extends ScreenElement

Inheritance enables me to specify different behaviour (HTML code, style, validation) without repeating myself. Trivial example:

ScreenElement::getTitle()
ScreenElement::getValue()
ScreenElement_Text::getMaxChars()
ScreenElement_Text_Money::getCurrency()

A problem is that these classes are now being used in different contexts than what they were originally intended (which was describing parts of forms): For example, as columns in tables or to describe information appearing in a calendar. Each context adds methods and properties to the classes that other usages don't need. Example:

When used in a form: getFormElement()
When used in a table: calculateColumnWidth()
When used in a calendar: getStartTime()

I now ask myself how to reduce the growing complexity! I'd like smaller, more specialized classes, but would not like to multiply the number of classes nor to duplicate code, but I can't get my head around this.

Was it helpful?

Solution

A solution, to avoid manipulating too complex structure, could be to use a Facade pattern. That is, for example: add the interfaces IScreenElement_Text_Area_Form, IScreenElement_Text_Area_Table and IScreenElement_Text_Area_Calendar.

Have ScreenElement_Text_Area implement those 3 interfaces, but only use the most relevant interface in a given context.

That way, a form will only manipulate a ScreenElement_Text_Area through an IScreenElement_Text_Area_Form, so it will only be able to access getFormElement(), but not the other two methods.

That being said, it's just one possible solution. You could also, for example, want to have a look at composition over inheritance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top