5 Fuse similar code together

 

This chapter covers

  • Unifying similar classes with Unify similar classes
  • Exposing structure with conditional arithmetic
  • Understanding simple UML class diagrams
  • Unifying similar code with Introduce strategy-pattern (P5.4.2)
  • Removing clutter with No interface with only one implementation (R5.4.3)

In the previous 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 pattern: Unify similar classes

5.2 Unifying simple conditions

5.2.1 Refactoring pattern: Combine ifs

5.3 Unifying complex conditions

5.3.1 Using arithmetic rules for conditions

5.3.2 Rule: Use pure conditions

5.3.3 Applying condition arithmetic

5.4 Unifying code across classes

5.4.1 Introducing UML class diagrams to depict class relations

5.4.2 Refactoring pattern: Introduce strategy pattern

5.4.3 Rule: No interface with only one implementation

5.4.4 Refactoring pattern: Extract interface from implementation

5.5 Unifying similar functions

5.6 Unifying similar code

Summary