[英]Refactoring a Private Utility Method in Java
我正在嘗試重構 Java 中的兩個私有方法,它們本質上是同一件事。 我目前正在對足球決勝局進行一些 JUnit 測試斷言,並編寫了一個實用方法,該方法可以流式傳輸結果並返回團隊得分或失球的總進球數。 它們非常相似:
private Integer getTeamGoalsScored(final LeagueTable leagueTable, final Team team) {
return leagueTable.getAllResults().stream()
.filter(t -> t.getHomeTeam().equals(team))
.map(Result::getOutcome)
.map(Outcome::getGoalsScoredByHomeTeam).reduce(0, Integer::sum) +
leagueTable.getAllResults().stream()
.filter(t -> t.getAwayTeam().equals(team))
.map(Result::getOutcome)
.map(Outcome::getGoalsScoredByAwayTeam).reduce(0, Integer::sum);
}
private Integer getTeamGoalsAgainst(final LeagueTable leagueTable, final Team team) {
return leagueTable.getAllResults().stream()
.filter(t -> t.getHomeTeam().equals(team))
.map(Result::getOutcome)
.map(Outcome::getGoalsScoredByAwayTeam).reduce(0, Integer::sum) +
leagueTable.getAllResults().stream()
.filter(t -> t.getAwayTeam().equals(team))
.map(Result::getOutcome)
.map(Outcome::getGoalsScoredByHomeTeam).reduce(0, Integer::sum);
}
如您所見,它們基本上是樣板文件,我想知道如何將這兩者合並為一種方法。 我猜 boolean 是真/假,得分/反對?
您可以提取執行過濾器和 map 的函數。並將它們作為參數傳遞給這個 function:
private Integer getSum(final LeagueTable leagueTable,
Function<Result, Boolean> filterFun, Function<Outcome, Integer> mapFun
) {
return leagueTable.getAllResults().stream()
.filter(filterFun)
.map(Result::getOutcome)
.map(mapFun).reduce(0, Integer::sum);
}
然后你可以像這樣在你的代碼中使用:
private Integer getTeamGoalsScored(final LeagueTable leagueTable, final Team team) {
return getSum(leagueTable,
t -> t.getHomeTeam().equals(team), Outcome::getGoalsScoredByHomeTeam) +
getSum(leagueTable,
t -> t.getAwayTeam().equals(team), Outcome::getGoalsScoredByAwayTeam);
}
正如在對ToIntFunction
和Predicate
的評論中提到的那樣; getSum
可以這樣寫:
private Integer getSum(final LeagueTable leagueTable,
Predicate<Result> filterFun, ToIntFunction<Outcome> mapFun
) {
return leagueTable.getAllResults().stream()
.filter(filterFun)
.map(Result::getOutcome)
.mapToInt(mapFun).sum();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.