簡體   English   中英

Java重構代碼的味道

[英]Java refactoring code smells

得到的反饋是,我需要提高重構/消除代碼氣味的技能。

  1. 我需要簡短的練習來 Java的答案來檢測和如何改善最常見的代碼氣味

  2. 例:

     public class Calculator { public long sum(int min, int max) { long result = 0; for (int i = min ; i <= max ; i++) result += i; return result; } public long sumOfSquares(int min, int max) { long result = 0; for (int i = min ; i <= max ; i++) result += i * i; return result; } } 

然后是最佳/最便捷的解決方案。 順便說一句,您可以立即向我展示該重復的最佳解決方案,/ \\也許使用運算符lambda“->”

謝謝!

您可以嘗試兩種方法合並為一個。 因為他們兩個看起來像

public long sum(long min, long max) {
    long result = 0;
    for (int i = min ; i <= max ; i++)
        result += someOperation(i);
    return result;
}

您可以允許用戶提供一些將計算i運算,因此它可以是ii+2i*i

這種策略可以是LongUnaryOperator接口的實現,在LongUnaryOperator接口中,用戶將需要實現long applyAsLong(long operand)方法。

因此,除了兩種方法,您還可以擁有一種看起來像

public static long sum(long min, long max, LongUnaryOperator mapper) {
    long result = 0;
    for (long i = min ; i <= max ; i++)
        result += mapper.applyAsLong(i);
    return result;
}

你可以像這樣使用它

sum(1, 4, i -> i * i)//sum of squares

i->i*i是lambda表達式,它實現了功能接口LongUnaryOperator並提供了其抽象的applyAsLong方法的實現,該方法將在我們的代碼中使用。 換句話說,它將i映射到i*i

更多用法示例:

sum(1, 4, i -> 2 * i)//sum of doubled values
sum(1, 4, i -> i)//sum of original values
//i->i can be also returned with `LongUnaryOperator.identity()`
//so you can rewrite your code into something like 
sum(1, 4, LongUnaryOperator.identity())

您還可以使用以下流重寫代碼

public static long sum(long min, long max, LongUnaryOperator mapper) {
    return LongStream.rangeClosed(min, max).map(mapper).sum();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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