2 minute read

In one of Uncle Bob’s video, he talked about this game called “Master Mind” when he was teaching Single Responsibility Principle(SRP). After googled the game, turns out that it is actually a quite famous board game. For more information about the game, please look here -> wiki.

The game can be played by two people. One comes up with a code, the other one tries to guess. The one who comes up with the code has to score the guesser’s guess based on some rules. The rules are the following:

  1. For each exact match(the right char on the right position), give a +.
  2. For each half match(the right char on the wrong position), give a -.

For example, if the code is ACBB and the guess is BCAF, then the score would be +--. The + is for the C, and two - are for B and A.

After explaining how to play this game, Uncle Bob gives a architecture that looks like this.

This design shows that there are 3 actors in this program: Customer, Game Designer and Strategist. According to the Single Responsibility Principle, there will be one module for each actor. And the Game Interface module and Strategy module are dependent on Game Play module.

Here shows a more detailed design.

Let’s use these as a reference and create some empty classes and interfaces.

source code version 0

Since the center of the program is the game engine, let’s implement enough GameEngine so that we can pass the test gotItOnFirstGuess.

source code version 1

And it’s not very hard to pass the test of gotItOnSecondGuess.

source code version 2

Then the test of neverGetIt.

source code version 3

Now, let’s write tests for the Guesser. If all the guesses are invalid, the nextGuess should return null.

source code version 4

If there is only one guess is valid, nextGuess should return that one and no more.

source code version 5

Next, test how the Guesser generate guesses.

source code version 6

Tests for the Scorer.

source code version 7

Finally, tests for RememberingGuessChecker. source code version 8

comments powered by Disqus