In the previous blog we refactored the "if logic" into an enum. The FrameType enum then knew how to calculate the score for the frame with the appropriate point bonus for strikes and spares.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum FrameType { | |
STRIKE { | |
public int scoreFrame(int rolls[], int frameIndex) { | |
return MAX_PINS + rolls[frameIndex+1] + rolls[frameIndex+2]; | |
} | |
public int rollsInFrame() { | |
return 1; | |
} | |
}, | |
SPARE { | |
public int scoreFrame(int rolls[], int frameIndex) { | |
return MAX_PINS + rolls[frameIndex+2]; | |
} | |
public int rollsInFrame() { | |
return 2; | |
} | |
}, | |
OPEN { | |
public int scoreFrame(int rolls[], int frameIndex) { | |
return rolls[frameIndex] + rolls[frameIndex+1]; | |
} | |
public int rollsInFrame() { | |
return 2; | |
} | |
}; | |
public static FrameType classifyFrame(int firstRoll, int secondRoll) {...} | |
public abstract int scoreFrame(int[] rolls, int frameIndex); | |
public abstract int rollsInFrame(); | |
} |
The scoreFrame logic is moved into a java.util.function.BiFunction instance. BiFunction<T, U, R> is a function that takes two objects, of type T and U. and returns an Object of type R. The lambda is supplied as an argument in the constructor and kept as a member of the enum instance.
The scoreFrame method changes from abstract to simply applying the function and returning the result. No changes in the BowlingGame class that uses the enum.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum FrameType { | |
STRIKE((rolls, frameIndex) -> MAX_PINS + rolls[frameIndex+1] + rolls[frameIndex+2], | |
1), | |
SPARE((rolls, frameIndex) -> MAX_PINS + rolls[frameIndex+2], | |
2), | |
OPEN((rolls, frameIndex) -> rolls[frameIndex] + rolls[frameIndex+1], | |
2); | |
private BiFunction<int[], Integer, Integer> scoreFunction; | |
private int rollsInFrame; | |
private FrameType(BiFunction<int[], Integer, Integer> scoreFunction, | |
int rollsInFrame) { | |
this.scoreFunction = scoreFunction; | |
this.rollsInFrame = rollsInFrame; | |
} | |
public static FrameType classifyFrame(int firstRoll, int secondRoll) {...} | |
public int scoreFrame(int[] rolls, int frameIndex) { | |
return scoreFunction.apply(rolls, frameIndex); | |
} | |
public int rollsInFrame() { | |
return rollsInFrame; | |
} | |
} |
No comments:
Post a Comment