저번 주 만든 리그 랭크 산정 기능에 대해 피드백이 있어서 수정했다.
리그 내 랭킹 업데이트 로직에서 플래그를 많이 이용했는데, 플래그 함수 남발은 가독성도 좋지 않고 실수를 유발할 확률이 높다.
실제로 튜터님도 엔티티 코드까지 가서야 어떤 내용인 지 확인할 수 있으셨다 하고, 사실 나도 며칠 후 보니 헷갈리는 느낌이 들었다.
원래 코드
public void updateStats(
int points, int goalsFor, int goalsAgainst,
boolean isWin, boolean isLoss, boolean isDraw
) {
this.teamScore += points;
this.totalScore += goalsFor;
this.totalLoss += goalsAgainst;
if (isWin) {
this.winCnt++;
}
if (isLoss) {
this.defeatCnt++;
}
if (isDraw) {
this.drawCnt++;
}
}
private void updateTeamStats(LeagueGame lg) {
League league = lg.getLeague();
Game game = lg.getGame();
LeagueTeam homeTeam = findLeagueTeamByTeamIdAndLeagueId(game.getHomeTeamId(),
league.getLeagueId()
);
LeagueTeam awayTeam = findLeagueTeamByTeamIdAndLeagueId(game.getAwayTeamId(),
league.getLeagueId()
);
int homeScore = lg.getHomeScore();
int awayScore = lg.getAwayScore();
int winPoint = 3;
int defeatPoint = 0;
if (homeScore > awayScore) {
homeTeam.updateStats(winPoint, homeScore, awayScore, true, false, false);
awayTeam.updateStats(defeatPoint, awayScore, homeScore, false, true, false);
} else if (homeScore < awayScore) {
homeTeam.updateStats(defeatPoint, homeScore, awayScore, false, true, false);
awayTeam.updateStats(winPoint, awayScore, homeScore, true, false, false);
} else {
int drawPoint = 1;
homeTeam.updateStats(drawPoint, homeScore, awayScore, false, false, true);
awayTeam.updateStats(drawPoint, awayScore, homeScore, false, false, true);
}
}
변경 코드
public void updateStats(
int points, int goalsFor, int goalsAgainst
) {
this.teamScore += points;
this.totalScore += goalsFor;
this.totalLoss += goalsAgainst;
}
public void incrementWin() {
this.winCnt++;
}
public void incrementDefeat() {
this.defeatCnt++;
}
public void incrementDraw() {
this.drawCnt++;
}
private void updateTeamStats(LeagueGame lg) {
League league = lg.getLeague();
Game game = lg.getGame();
LeagueTeam homeTeam = findLeagueTeamByTeamIdAndLeagueId(game.getHomeTeamId(),
league.getLeagueId()
);
LeagueTeam awayTeam = findLeagueTeamByTeamIdAndLeagueId(game.getAwayTeamId(),
league.getLeagueId()
);
int homeScore = lg.getHomeScore();
int awayScore = lg.getAwayScore();
int winPoint = 3;
int defeatPoint = 0;
int drawPoint = 1;
if (homeScore > awayScore) {
homeTeam.updateStats(winPoint, homeScore, awayScore);
homeTeam.incrementWin();
awayTeam.updateStats(defeatPoint, awayScore, homeScore);
awayTeam.incrementDefeat();
} else if (homeScore < awayScore) {
homeTeam.updateStats(defeatPoint, homeScore, awayScore);
homeTeam.incrementDefeat();
awayTeam.updateStats(winPoint, awayScore, homeScore);
awayTeam.incrementWin();
} else {
homeTeam.updateStats(drawPoint, homeScore, awayScore);
homeTeam.incrementDraw();
awayTeam.updateStats(drawPoint, awayScore, homeScore);
awayTeam.incrementDraw();
}
}
성능과 동작상의 차이 없이 아래와 같은 이점이 있다.
가독성 증가
조건문 단순화
메서드의 단일 책임 원칙 준수
updateStats는 다양한 조건을 처리하는 복합적인 책임이 있었음