code4nothing/singlepath — pull request #5 by arialdomartini (2014-07-22 08:05:53+00:00)
Title: Quiz #1 - Using a DefaultMap as lookup table and a Strategy Pattern.

Ok, I succeeded at removing all the conditional paths, but the resulting code is both much longer and (maybe) awful.

The idea is: the 3 paths are encapsulated into 3 separate classes, all sharing the same interface ```Strategy```: we have

* the ```NullStrategy``` returning ```null```
* the ```DoubleStrategy``` returning the string repeated twice
* the ```ErrorStrategy``` returning the string ```error```.

The class ```Formatter``` asks for permission, as usual, then asks for the the right strategy (based on the received permission) from the lookup dictionary

```
String response = service.askForPermission();
Strategy strategy = strategies.get(response);
```

and then it delegates the execution of the job to the selected strategy

```
return strategy.workOn(theInput);
```

As you see, no ```if```s at all.

Two notes:

1. The Formatter is completely unaware of which strategy is used, since it's completely decoupled from it (it knows the strategy only in terms of interface)
2. As @peachofpersia noted, there's a hidden ```if``` in the use of ```DefaultedMap```.

Is it a better design than the orginal one? I wonder. I'm looking forward to hearing from you.