Skip to content

Conversation

@arialdomartini
Copy link
Contributor

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 ifs 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.

@arialdomartini arialdomartini changed the title Quiz #1 - Using a DefaultMap as lookup table and a Strategy Pattern. Proposal #1 - Using a DefaultMap as lookup table and a Strategy Pattern. Jul 22, 2014
@arialdomartini
Copy link
Contributor Author

For those who are not too much fluent with GitHub flow: in order to make someone's Pull Request available on your local repository, do this:

  • Since a pull request contains a bunch of commits that haven't yet been merged to the main repository, but are still hosted on the user's repo, connect your repo with the user's repo
git  remote add luchino https://github.com/luchino/singlepath
  • then get the new commits
git fetch luchino

Now, your repo contains all the luchino's commits, and a bunch of new remote branches, named luchino/master, luchino/foobar and so on.

@arialdomartini arialdomartini changed the title Proposal #1 - Using a DefaultMap as lookup table and a Strategy Pattern. Solution #1 - Using a DefaultMap as lookup table and a Strategy Pattern. Jul 23, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant