If I inherit from a base class, is there a rule which states “only inherit where you need to implement/use all (or X%) of the base classes functionality/methods”? I understand that if I inherit then I have inherited the lot, but that doesn’t mean I have to use it all.
Assume the following pattern:
public abstract class Template
{
public void LoadCustomer()
{
//Load customer logic
}
public virtual void LoadGrid()
{
//Logic
}
public virtual void other()
{ //logic }
public virtual void other2()
{ //logic }
public virtual void other3()
{ //logic }
public string WelcomeMessage()
{
//perform lots of complex logic
return "Hello and welcome";
}
}
If part of my application wants to only show the WelcomeMessage(), would it be wrong to inherit from the Template class above (I know I can only inherit once but that isn’t factor for this question) (also note, I’ve purposely not included any abstract methods/fields).
I went down this road on quite a few of my projects before I “saw the light.”
Yes and no. No that there is no rule, but yes that there is a way to do what you want to do. It’s call favoring composition over inheritance and what that means is that you need to break off each block of functionality into a single class, and then (in what is currently your sub-classes) create an instance of that class and then delegate the needed work to it. Using this technique will allow you to easily make modifications to what is currently your super-class without having ripple effects on your current sub-classes.
Bottom line, when in doubt (or if it just feels funny) don’t use inheritance. This is embodied by the Liskov substitution principle which states that any sub-class should be a full and proper substitute for it’s super class. (i.e. don’t have
BoatsubclassPlanejust because they can both carry people).For more fun reading, check out the SOLID software engineering paradigm.