Java重构代码

Java重构代码,java,coding-style,refactoring,Java,Coding Style,Refactoring,我得到的反馈是,我需要提高重构/删除代码的技能 我需要一些简短的练习来检测和改进最常见的代码气味 带有java中的答案 例如: public class Calculator { public long sum(int min, int max) { long result = 0; for (int i = min ; i <= max ; i++) result += i; return result;

我得到的反馈是,我需要提高重构/删除代码的技能

  • 我需要一些简短的练习来检测和改进最常见的代码气味 带有java中的答案

  • 例如:

    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;
        }
    
    }
    
    公共类计算器{
    公共长和(最小整数,最大整数){
    长结果=0;
    对于(inti=min;i您可以尝试将两种方法合并到一个中

    public long sum(long min, long max) {
        long result = 0;
        for (int i = min ; i <= max ; i++)
            result += someOperation(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();
    }
    

    从分离普通代码和非普通代码开始。顺便说一句,
    ->
    不是alpha,而是lambda:)当然这是有效的,但重复只会伤害眼睛,这两种方法在我(初中生)中几乎相同意见:1)在长循环中添加整数?2)在for循环中没有大括号。但我不会称之为代码气味。哦,天哪,当然了:重复相关书籍:。
    public static long sum(long min, long max, LongUnaryOperator mapper) {
        return LongStream.rangeClosed(min, max).map(mapper).sum();
    }