I just wanted to have a post that said that to try and counterbalance all the “inheritance is evil” posts I see. There’s one linked on the HackerNews front page today, but it is just another in a long string that started at about the same time OO was introduced.
I don’t think the problem is with inheritance. I think the problem is with the very narrow views of software technologies that many in our industry have. See, inheritance is just a tool, and is no different in essence from many of the tools we use: closures, iterators, functions, interfaces, etc. You have to know how to use every tool. What I mean, more precisely, is:
- Know what the tool expresses. Don’t try to use it to express something it wasn’t meant to express.
- Know the tool’s weaknesses. Always balance against the strengths.
- Know the types of design situations where it is useful. Always realize that in any situation more than one tool might be applicable.
- Know what you’re talking about. If you only have experience in one little niche of the software world (even if it’s a big niche), don’t make sweeping generalizations.
The article I mentioned above complains about inheritance because it “forces an is-a relationship”. Yes, yes, it does. That’s what inheritance means. The article goes on to describe some perfectly valid alternatives involving the use of strategies that, in the narrow context in which they are described, seem to make sense. But that in no way proves the article’s point that inheritance is evil.
Our industry is not:
- Web page design
- Line of business applications
- Embedded systems
- Mobile games
- Mobile line of business apps
- Database front-ends
- Social networks
- Big data repositories
- Open source
It’s actually all of these, and more. So when we make statements of tool preferences or applicability, we need to make sure that the broadness of our statements matches the broadness of the industry, or take care to scope our claims to the appropriate context and environment.
I maintain that inheritance is a useful tool when used to model the types of relationships it is meant to model. While it is true that specific designs might use inheritance in violation of its intent, this is not a problem with inheritance, but with designers ignoring or, more probably, not really understanding the appropriate uses of inheritance.
Our industry is incredibly rich and varied, and simple-minded global positions like X is evil/great are neither helpful nor well-informed.