Horizontal reuse: An alternative to inheritance

In class-based object-oriented programming it is common to refactor classes that appear to share some functionality into two subclasses of a common base class, thus avoiding repetition.

Using a farm model as an example, the Horse class and the Tractor class each implement a pull_plough method. This would make it a candidate for subclassing, for instance into a Hitchable class for Horse and Tractor to each inherit from.

But what if Horse already inherits from Animal, and Tractor already inherits from Vehicle? What we want is to package up the pull_plough behaviour in one place where the bundle of behaviour can be documented, and give it a name so code can check whether an object implements this bundle of behaviour.

Java offers interfaces for this purpose, but could it be that what you really need is a Moose?

Read more at O'Reilly – Programming...

Join the discussion
Be the first to comment on this article. Our Commenting Policies