Articles : clean code

Refactoring Conditional Structures with Map

When working on already existing codebases, I often encounter pieces of code that look like this:

public class Day {
  public void start(Weather weather) {
    switch(weather) {
      case RAINY:
          takeAnUmbrella();
          break;
      case SUNNY:
          takeAHat();
          break;
      case STORMY:
          stayHome();
          break;
      default:
          doNothing();
          break;
    }
  }
}

Basically, depending on the weather, an action has to be taken. This kind of code is pretty hard to test and to maintain. The goal of this article is to refactor it using a Map.

clean code, java, refactoring