chapter five

5. Unifying code to simplify and enable reuse

 

This chapter covers:

  • Unifying similar classes with Unify similar classes [P5.1.1]
  • Exposing structure with conditional arithmetic
  • Understanding simple UML class diagrams
  • Unifying similar code with Replace type code with classes [P5.4.2]
  • Removing clutter with Unify similar classes [P5.4.3]

In the last chapter, I mentioned that we are not finished with updateTile. It violates several rules, most notably Never use if with else [R4.1.1]. We also worked to preserve the ||s in the code because they expressed structure. In this chapter, we explore how to expose more such structures in the code.

This is updateTile at the moment.

Listing 5. 1. Initial
function updateTile(x: number, y: number) {
  if ((map[y][x].isStone() || map[y][x].isFallingStone())
      && map[y + 1][x].isAir()) {
    map[y + 1][x] = new FallingStone();
    map[y][x] = new Air();
  } else if ((map[y][x].isBox() || map[y][x].isFallingBox())
      && map[y + 1][x].isAir()) {
    map[y + 1][x] = new FallingBox();
    map[y][x] = new Air();
  } else if (map[y][x].isFallingStone()) {
    map[y][x] = new Stone();
  } else if (map[y][x].isFallingBox()) {
    map[y][x] = new Box();
  }
}

5.1. Unifying similar classes

5.1.1. Refactoring: Unify similar classes

5.2. Unifying simple conditions

5.2.1. Refactoring: Combine ifs

5.3. Unifying complex conditions

5.3.1. Arithmetic of conditions

5.3.2. Rule: Use pure conditions

5.3.3. Using condition arithmetic

5.4. Unifying code across classes

5.4.1. UML Class Diagrams 101

5.4.2. Refactoring: Introduce strategy-pattern

5.4.3. Rule: No interface with only one implementation

5.4.4. Refactoring: Extract interface from implementation

5.5. Unifying similar functions

5.6. Unifying similar code

5.7. Summary