Advancing the Design With Two-letter Combinations
Learn how to incrementally add tests in Wordz for handling two-letter combinations and engaging in refactoring for clarity, readability and simplification.
We can proceed to add tests aimed at getting the code to handle two-letter combinations. This is an obvious step after getting the code to work with a single letter. To do this, we’ll need to introduce a new concept into the code: a letter can be present in the word, but not in the position we guessed it to be.
Let’s begin by writing a test for a second letter that’s in the wrong position:
@Testvoid secondLetterWrongPosition() {var word = new Word("AR");var score = word.guess("ZA");assertScoreForLetter(score, 1,Letter.PART_CORRECT);}
We’ll change the code inside the assess()
method to make this pass and keep the existing tests passing.
Implementing multi-letter logic
Let’s add an initial code to check all the letters in our guess:
public void assess(String attempt) {for (char current: attempt.toCharArray()) {if (isCorrectLetter(current)) {result = Letter.CORRECT;}}}private boolean isCorrectLetter(char currentLetter) {return correct.charAt(position) == currentLetter;}
The main change here is to assess all of the letters in attempt
and not assume it only has one letter in it. That, of course, was the purpose of this test—to drive out this behavior. By choosing to convert the attempt
string into an array of char
, the code seems to read quite well. This simple algorithm iterates over each char
using the current
variable to represent the current letter to be assessed. This requires the isCorrectLetter()
method to be refactored for it to accept and work with the char
input—well, either that or converting char
to a String
, and that looks ugly. The original tests for single-letter behaviors still pass, as they must.
Refining logic with triangulation
We know the ...
Get hands-on with 1400+ tech skills courses.