chapter four
4. Using objects to eliminate complex if statements
This chapter covers:
- Eliminating early binding with Never use
ifwithelseand Never useswitch
- Removing
ifstatements with Replace type code with classes and Push code into classes
- Removing bad generalization with Specialize method
- Preventing coupling with Only inherit from interfaces
- Removing methods with Inline method and Try delete then compile
At the end of last chapter, we had just introduced a handleInput function that we could not use Extract method [P3.2.1] on because we do not want to break up the else if chain. Unfortunately, handleInput is not compliant with our fundamental Five lines [R3.1.1] rule, so we cannot leave it as is.
Here’s the function:
Listing 4. 1. Initial
function handleInput(input: Input) {
if (input === Input.LEFT)
moveHorizontal(-1);
else if (input === Input.RIGHT)
moveHorizontal(1);
else if (input === Input.UP)
moveVertical(-1);
else if (input === Input.DOWN)
moveVertical(1);
}
4.1. A simple if statement
We are stuck. To show how we deal with else if chains like this, we start by introducing a new rule.
4.1.1. Rule: Never use if with else
Statement
Never use if with else, unless we are checking against a data type we do not control.