Factor implementation differences into subcomponents
m |
|||
Line 27: | Line 27: | ||
* [[Johnson and Foote 1988]] | * [[Johnson and Foote 1988]] | ||
* [[Don't repeat yourself]] | * [[Don't repeat yourself]] | ||
+ | |||
+ | [[Category: Johnson and Foote's heuristics]] |
Latest revision as of 01:33, 18 August 2009
This is Rule 10 in Johnson and Foote 1988: "If some subclasses implement a method one way and others implement it another way then the implementation of that method is independent of the superclass. It is likely that it is not an integral part of the subclasses and should be split off into the class of a component.
Multiple inheritance can also be used to solve this problem. However, if an algorithm or set of methods is independent of the rest of the class then it is cleaner to encapsulate it in a separate component. "
In other words, if different subclasses implement a method in one of several ways, then a new class hierarchy should be created to encapsulate this algorithm, and this should be composed in the superclass.
This means that multiple subclasses can contain the same implementation without repeated code.
An interesting point to note is that this rule is an early version of the Gang of Four Strategy pattern, obviously influenced by Johnson's contribution to the paper.
Example
Consider the following class diagram:
We can see that some subclasses of animals implement walk using two legs and others implement it with four legs.
According to Johnson and Foote's rule, we should factor this implementation difference into subcomponents, such as the following:
We can see that we now have no repeated code for the walk() method.