簡體   English   中英

重構 Java 中的私有實用程序方法

[英]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);
}

更新

正如在對ToIntFunctionPredicate的評論中提到的那樣; 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM