Thursday, September 15, 2016

Replace switch statements using lamda's

Complex switch statements with many possible cases tend to result in cluttered code. When code checkers start to complain about the complexity of a method, it becomes time to refactor that piece, but often that sounds simpler than it actually is.
With lambda's in java 8 these switch statements can easily be simplified resulting in cleaner, easier to read and extend code.
Lets take for example the below switch statement and turn that into a nice and easy to understand piece of code using a Map and some lamba expressions.

public List<string> findUsingSwitch(Bicycle bicycle) {
  switch (bicycle) {
    case RACE:
      return listRacers();
    case ATB:
      return listAtbs();
    case CITY:
      return listCityBikes();
    case HPV:
      return listHumanPoweredVehicles();
    default:
      throw new IllegalArgumentException();
    }
}

Its easy to imagine that such a switch statement can grow and become pretty complex.
In java 8 we now have the ability to use lambda expressions and pass them around to functions. This allows us to replace the switch/case block with a more flexible and more natural implementation.
Lets first start with creating a map that associates the enum with the lambda that produces the result for the given enum value.

private Map<Bicycle, Supplier<List<String>>> typeMap = new HashMap<Bicycle, Supplier<List<String>>>() {
  {
    put(Bicycle.RACE, () -> listRacers());
    put(Bicycle.ATB, () -> listAtbs());
    put(Bicycle.CITY, () -> listCityBikes());
    put(Bicycle.HPV, () -> listHumanPoweredVehicles());
  }
};

Now the find method can be changed to use the lambdas instead:

public List findUsingLambdas(Bicycle bicycle) {
  if (!typeMap.containsKey(bicycle)) {
    throw new IllegalArgumentException(String.format("%s is not supported", bicycle));
  }

  return typeMap.get(bicycle).get();
}


The example sources can be found on github

No comments: