Grow by addition

» Glossary » Grow by addition

«Code should grow by addition rather than mutation.»
Measuring the closure of code, Michael Feathers

This heuristic refers to the way in how new features are developed: modifying existing elements or creating new ones (objects, files, etc).

Specialization and delegation (inheritance and composition)

In the following example, a graphic editor, the logic of showing an element in the screen is centralized in the display() method. To add a new element, it is necessary to modify that method.

public void display() {
    switch (getType()) {
        case RECTANGLE :
            //...
            break;
        case OVAL :
            //...
            break;
        case TEXT :
            //...
            break;
        default :
            break;
        }
}

By means of specialization (inheritance) and delegation, it is possible to convert this conditional method in a messages system.

public void display() {
    getType().display();
}

Other links of interest:

  • In «Nothing is something», Santi Metz talks about inheritance, composition, and conditionals. The core idea is the same: to know when to use inheritance and when composition. Metz states she is infected by the way of thinking of Alan Kay‘s SmallTalk.
  • A common pattern in this context is the NullObjectPattern. See also SpecialCase by Martin Fowler. The core idea is to convert the null case in a domain object, preventing the need for conditionals that check if an object is null and helping the code to use more composition.
  • Volatility