Reputation: 8128
I am aware of the responses at Prefer composition over inheritance and am aware of the merits of composition over inheritance.
But there are cases where inheritance does have a good role to play. It's the incorrect use of inheritance hierarchy that causes all the issues related to reuse.
Take the example of the following controls...
Button/Textbox/Combobox/ListBox/Grid etc.
Typically they are implemented as
public class Control
{
...
}
public abstract class TextBoxBase : control
{
....
}
public class TextBox : TextBoxBase
{
....
}
public abstract class ButtonBase: control
{
....
}
public class Button: ButtonBase
{
....
}
public class TextBox : TextBoxBase
{
....
}
public class NumericTextBox: TextBox
{
....
}
NOTE: Both the UI and the functionlity is reusable.
I may be wrong or partially correct. Your thoughts would only help me improve my understanding of this subject.
How would you go about designing the control model/hierarchy without using inheritance, and which one do you think is better?
Please take into account the ease of use, use of IDE for this control as well.
P.S: This question is also inspired by this question.
Upvotes: 1
Views: 342
Reputation: 34711
You would use a series of delegates for functionality that is traditionally in the parent class. Say the Control class contains basic drawing functions (ie paint()) - well Control would become a BasicControlDelegate or similar, and the "subclasses" would be created with a reference to a BasicControlDelegate, which would be used for all "inherited" functionality.
If you want to use the parent/delegate functionality as-is, you create a paint() method in the each "subclass" which simply calls the same method on the delegate. If you want to change the functionality, you create a different implementation.
TextBoxBase may have a paint() implementation, which is used directly by TextBox, but perhaps NumericTextBox has its own paint() implementation.
I think the main points are these:
Upvotes: 1
Reputation: 1501586
Preferring composition isn't the same as mandating it in every situation. To add to your UI example, I'd say that both Java and .NET benefit from using an inheritance hierarchy for streams.
I suggest you have a look at the inheritance tree for Windows Presentation Foundation though - that's a relatively modern UI toolkit designed for composition. That enables weird and wonderful things - like buttons which contain further buttons etc. Sometimes (as in that example) it will be useless - but the general design is powerful.
I'm not saying I'm ideal - nor would I claim to know very much about WPF - but it's an interesting starting point.
I should point out that even within WPF inheritance is used extensively - but not in quite the same way as in (say) WinForms.
Upvotes: 2