Skip to content

Instantly share code, notes, and snippets.

@fteychene
Created March 29, 2016 14:00
Show Gist options
  • Save fteychene/0926591c010607d23180 to your computer and use it in GitHub Desktop.
Save fteychene/0926591c010607d23180 to your computer and use it in GitHub Desktop.
Tennis refactor proposal
public class TennisGame1 implements TennisGame {
private int scoreP1 = 0;
private int scoreP2 = 0;
private String player1Name = "player1";
private String player2Name = "player2";
public TennisGame1(String player1Name, String player2Name) {
this.player1Name = player1Name;
this.player2Name = player2Name;
}
public void wonPoint(String playerName) {
if (playerName.equals(player1Name))
scoreP1 += 1;
else
scoreP2 += 1;
}
public String getScore() {
if (scoreP1 == scoreP2) {
if (scoreP1 < 3) {
return pointsName(scoreP1) + "-All";
}
return "Deuce";
} else if (scoreP1 >= 4 || scoreP2 >= 4) {
return findWinnerOrAdvantage();
}
return pointsName(scoreP1) + "-" + pointsName(scoreP2);
}
private String findWinnerOrAdvantage() {
return Math.abs(scoreP1 - scoreP2) > 1 ? "Win for " + getPlayerWithMaxPoint() : "Advantage " + getPlayerWithMaxPoint();
}
private String getPlayerWithMaxPoint() {
return scoreP1 > scoreP2 ? player1Name : player2Name;
}
private static String pointsName(int points) {
switch (points) {
case 0:
return "Love";
case 1:
return "Fifteen";
case 2:
return "Thirty";
case 3:
return "Forty";
default:
return "";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment