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.
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.