From 5664f7fcf7820ce664abf86866a9364c5c66d4ee Mon Sep 17 00:00:00 2001 From: Thomas Papendieck Date: Wed, 28 Nov 2018 18:11:18 +0100 Subject: [PATCH] production code refactored --- .../hsfulda/ciip/tdd/BownlingCalculator.java | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/TDD-pure-function/src/main/java/de/edu/hsfulda/ciip/tdd/BownlingCalculator.java b/TDD-pure-function/src/main/java/de/edu/hsfulda/ciip/tdd/BownlingCalculator.java index c732390..81f4955 100644 --- a/TDD-pure-function/src/main/java/de/edu/hsfulda/ciip/tdd/BownlingCalculator.java +++ b/TDD-pure-function/src/main/java/de/edu/hsfulda/ciip/tdd/BownlingCalculator.java @@ -4,18 +4,34 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class BownlingCalculator { + private static final int PINS_IN_FRAME = 10; + private static final String SPARE = "(\\d)/ (\\d)"; + private static final String INCOMPLETE_FRAME = "\\d"; + + @FunctionalInterface + private interface FrameCalculator { + int evaluate(Matcher frameStructure); + } + + private static final int SPARE_FRAME_FOLLOWING_THROW = 2; + private static final int SPARE_FRAME_FIRST_THROW = 1; public int evaluate(String listOfThrows) { int sum = 0; - Matcher singleDigit = Pattern.compile("\\d").matcher(listOfThrows); - while (singleDigit.find()) { - sum += Integer.parseInt(singleDigit.group()); - } - singleDigit = Pattern.compile("(\\d)/ (\\d)").matcher(listOfThrows); + sum += evaluateFrames(listOfThrows, INCOMPLETE_FRAME, m -> Integer.parseInt(m.group())); + sum += evaluateFrames(listOfThrows, SPARE, m -> PINS_IN_FRAME// + - Integer.parseInt(m.group(SPARE_FRAME_FIRST_THROW)) + + Integer.parseInt(m.group(SPARE_FRAME_FOLLOWING_THROW))); + return sum; + } + + private int evaluateFrames(String listOfThrows, String frameStructurePattern, FrameCalculator frameCalculator) { + Matcher singleDigit = Pattern.compile(frameStructurePattern).matcher(listOfThrows); + int frameValue = 0; while (singleDigit.find()) { - sum += 10 - Integer.parseInt(singleDigit.group(1)) + Integer.parseInt(singleDigit.group(2)); + frameValue += frameCalculator.evaluate(singleDigit); } - return sum; + return frameValue; } }