The current project – trying to port a web application I didn’t write from Apache 1 to Apache 2, and in the process getting my head around its bewilderingly complicated class hierarchy – has crystallised my already dim view of inheritance into the following principle:
If you are relying on deep inheritance, it’s a sign that you are modelling the wrong things.
I reckon objects should represent real world entities – Students, Customers, Parts etc. But inheritance isn’t often a useful property of real world objects; it’s a property of the abstractions we use to think about those objects. The sun ISA sphere, and so ISA orange, but that fact is not really the most important observation we can make about those two things.
One-level-deep inheritance (an orange ISA fruit, or, even more usefully, ISA pricelist-item) is handy, but inheritance of this sort – where a flat array of specific objects all inherit from a single template – is more like a way of filling in properties than anything else.
Deep inheritance may be better when the application domain is itself code: compilers and parsers etc.
In the code I’m grappling with, the classes are modelling application states and state machines and so on: the things the programmer is thinking about, not the things out in the world that the code is dealing with. Inheritance is a natural fit for such things, but that just makes it harder to read the code. While good code might be a possible outcome for some programmers using this approach, I think it’s the exception rather than the rule.
May 22, 2009 at 3:56 am
[...] for this code, the family of classes is not called X::Y::Z::Report, but X::Y::Z::Sort, and tracing the inheritance relationships is a nightmare. So it’s not like modelling business concepts is going to make you write good [...]