Switch to Map

Calofir Emil
2 min readJul 11, 2020

Using the simplicity of Map data structure can save you some sleep.

Exploring Clojure and Rich Hickey talks I start to value the simplicity and power of Maps. They are so elegantly used in programs written in Clojure. And I find ways to “abuse” them in Java.

OK, so I’m using a pattern in Java 8 to replace switch-case or spamming armies of classes to get the right function implementation.

The Keys:

enum Direction {LEFT, RIGHT, UP, DOWN, UP_LEFT}

The pure functions with two types of declaration:

func calculateLeft = (Position position) -> {/*returns points*/ };
func calculateRight = (Position position) -> {/*returns points*/};
List<Point> calculateUp(Position position){ /*returns points*/ }
List<Point> calculateDown( Position position){ /*returns points*/}

The mapping: enum to behavior

final Map<Direction, func> switchDirectionType = Map.of(
LEFT, calculateLeft,
RIGHT, calculateRight,
UP,this::calculateUp,
DOWN,this::calculateDown);

The helper: is optional we can use Function or BiFunction

@FunctionalInterface
interface func {
List<Point> apply(final Position position);
func empty = (a) -> Collections.emptyList();
}

The usage:

Position position = new Position(...);
List<Point> points = switchDirectionType
.getOrDefault(LEFT, func.empty)
.apply(position);

That is it.

As you can see we map functions of the different implementation to some constants.

The null case is handled by the Map getOrDefault method.

I think this is very flexible and easy to write. No class overloading, just map behavior to keys and then select and apply input parameters.

We map as much as we need, where we need it.

--

--