Just In Time Inheritance

Premise for Discussion: Only create inheritance trees after you've duplicated code.

Inheritance is one of the most powerful tools in OO design, but it's also commonly misunderstood, and it causes confusion for OO newbies.

A good principle for minimizing unnecessary inheritance is to do JustInTimeInheritance. In JustInTimeInheritance, you never write the superclass first. You always write the potential subclasses first, and you only create the superclass when you have duplicated code between two potential subclasses.

Superclasses can be demystified if you treat them as a simple code sharing mechanism.

Other views:

Inheritance is not just a code sharing principle. With behavioral inheritance, you are deliberately expressing the idea that the subclass inherits the behavior of the superclass and can replace the superclass in certain situations.

(major edit there, hope it still expresses what original poster was trying to say)


Are you all Smalltalk hackers or what? Surely we need to distinguish between Class inheritance, and Type inheritance

Classes are all about implementation. So JustInTimeInheritance is spot on for classes.

Types are all about interfaces and the ability to substitute one implementation for another. Here we need a sound framework of concepts to underly our inheritance hierarchy, not just the arbitrary results of the latest refactoring exercise.

-- StephenHutchinson

JustInTimeInheritance works just as well for type inheritance. You don't need an interface unless code needs to treat two different classes polymorphically. As soon as that is the case, extract the methods that must be polymorphic into an interface and make the two classes implement that interface. As development and refactoring shows that more methods need to be added to the interface, or if some callers or called classes need less methods, split the interface into separate concepts. --NatPryce


CategoryTime CategoryLazyPattern


EditText of this page (last edited December 8, 2014) or FindPage with title or text search