Factor implementation differences into subcomponents

From CSSEMediaWiki
Jump to: navigation, search

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:

FactorDiff1.png

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:

FactorDiff2.png

We can see that we now have no repeated code for the walk() method.

See Also

Personal tools