Inheritance Sucks!

Not really, of course, its just very easy to misuse, and used way too much. I’m talking about object inheritance (‘extends‘) here. Object inheritance should only be used to override behaviour, not state. If the only reason a class extends another is to get all its fields, that’s the wrong thing to do. That’s what object composition is for. If you want a one to one mapping to another class, include it as a field and add delegators for its public methods to your interface. In IntelliJ there’s even a menu option for it. What about polymorphism you cry? Thats what interface inheritance is for. If you need to be able to polymorphically pass your composed object to methods that expect your contained object, implement a common interface and make your methods accept that instead. Your code will be cleaner, more modular and (most importantly) less coupled. The title of this post should probably have been ‘Coupling Sucks’. Extending a class binds you to it far more tightly than wrapping it as a field. And working through interfaces makes testing a snap. Just plug your testcase in, or a full-fledged mockobject, although I rarely need a full Mock when I can just write MyTestCase extends TestCase implements Foo, Bar, Baz {...} and make the assertions directly based on which methods were called and in what sequence.

Most code uses inheritance more often than object composition, and much of the time composition would have been the better option. I suspect the reason is as prosaic as the fact that object composition involves more typing. This is no longer the case with IDE’s like IDEA.

4 thoughts on “Inheritance Sucks!

  1. What you are talking about is the Delegation design pattern described by Mark Grand in his Patterns in Java Volume 1 book.

  2. ‘behaveslike’: brilliant. I was thinking of something like ‘isATypeOf’ instead of extends, and ‘is’ instead of implements, which would give you: public class Car isATypeOf Vehicle is Driveable.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s