It feels nice when adding new features, but don't forget about refactoring! 💯
Brief
On top of the current implementation, we want to add a new feature.
We want to give the users the opportunity to use their own delimiters between numbers.
- To add a custom delimiter, the beginning of the string will contain a separate line. So the input will look like this:
//[delimiter]\n[numbers…]
- for example
//;\n1;2
should return 3
where the custom delimiter is ;
- The first line
//[delimiter]\n
should be optional. All existing scenarios should still be supported.
Implementation
As we're already used by now, we'll start with a test:
@Test
void testCalculator_CustomDelimiter() {
StringCalculator stringCalculator = new StringCalculator();
String input = "//;\n1;2";
Assertions.assertEquals(3, stringCalculator.add(input));
}
🔴 Of course, the test will fail, telling us that the input is not something the application can handle.
🔵 At this moment, we start thinking about an implementation.
The first thing coming to mind is to use a RegEx to match the new type of input.
If the input matches the pattern, we'll extract the new delimiter and we'll use it to split the numbers.
If not, we'll assume that the input came in the old format, and we'll use the current implementation.
🔵 To do that, we need to:
- Define the actual regular expression used to extract the delimiter and the numbers:
//(.*)\\n(?<numbers>\\S*)
- Add a new
SplitStringStrategy
to the StringSplitter
based on the extracted delimiter. - Split numbers and calculate the sum like we did until now.
🔵 Add a method to the StringSplitter
so that we are able to add a new StringSplitStrategy
, next to the default ones.
🔵 Add the logic to the StringCalculator
to match the pattern.
🟢 Run all the tests again and see them turning green. 🚀
Refactoring
We can now go a step further and do a bit of refactoring.
Let's create a DelimiterMatcher
class which will hold the responsibility of matching and extracting the groups from the input.
Because we want to return both delimiter
and numbers
values, we will need a DTO to store the two.
A bit of cleaning in the StringSplitter
too.
And now, putting it all together.
You can find the full project with the rest of the tests here: https://github.com/andreiszu/tdd-kata
💡
Don't miss out on more posts like this! Susbcribe to our free newsletter!
💡
Currently I am working on a Java Interview e-book designed to successfully get you through any Java technical interview you may take.
Stay tuned! 🚀