Code Refactoring Techniques Duplicate Code

In the process of our project development, sometimes it is easy to write and write. For some business codes, we have to repeatedly write them, so that when we need to modify them later, we have to find these repeated codes everywhere in the whole project, which is really a bad thing.

1. Duplicate code

definition

Duplicate code does not refer to exactly the same code. As long as there is a piece of code or business processing, it can be called duplicate code.

Influence

Too much repetitive code will make the code too long and difficult to read, and if the code logic needs to be modified, it will make the code easy to miss and difficult to maintain.

Second, the case of repeated code

2.1 Code duplication between multiple methods of the same class

There are the following codes, which need to calculate the price of fruits. The price calculation formula of ordinary water pipes is the price of fruit quantity and the price of discounted products is the quantity of fruit and fruit price * discount. It can be seen that the following code, the logic of calculating the price according to the type of fruit is Repeat, if the price of the fruit changes, each method has to change.

/**
 * 计算水果总价(同一个类的两个函数含有相同的表达式)
 *
 */
public class FruitsCost {
    
    
    public double computeMoneyWithoutPrivileges(String type, int numbers) {
    
    
        double prices;
        switch (type) {
    
    
            case "apple":
                prices = 5.5;
                break;
            case "banana":
                prices = 4.0;
                break;
            case "strawberry":
                prices = 10.5;
                break;
            default:
                throw new IllegalArgumentException("Illegal type : " + type);
        }
        return prices * numbers;
    }
    public double computeMoneyWithPrivileges(String type, double numbers, double discount) {
    
    
        double prices;
        switch (type) {
    
    
            case "apple":
                prices = 5.5;
                break;
            case "banana":
                prices = 4.0;
                break;
            case "strawberry":
                prices = 10.5;
                break;
            default:
                throw new IllegalArgumentException("Illegal type : " + type);
        }
        return prices * numbers * discount;
    }
}

Solution
For code duplication between multiple methods of the same class, you can use the method of extracting functions. The following mainly introduces how to use IDEA development tools to quickly extract functions and refuse to extract them manually!
1: Select the code segment to be refined
insert image description here
2. Use the shortcut keys Ctrl + Alt + M, the following window will pop up
insert image description here
3. Click OK, replace other similar code segments one by one, select Replace, and replace all selections at one time All.
insert image description here
Refactor The finished code is as follows:

public class FruitsCost {
    
    
    public double computeMoneyWithoutPrivileges(String type, int numbers) {
    
    
        double prices = getPrices(type);
        return prices * numbers;
    }

    private double getPrices(String type) {
    
    
        double prices;
        switch (type) {
    
    
            case "apple":
                prices = 5.5;
                break;
            case "banana":
                prices = 4.0;
                break;
            case "strawberry":
                prices = 10.5;
                break;
            default:
                throw new IllegalArgumentException("Illegal type : " + type);
        }
        return prices;
    }

    public double computeMoneyWithPrivileges(String type, double numbers, double discount) {
    
    
        double prices = getPrices(type);
        return prices * numbers * discount;
    }
}

2.2 Duplication of code in subclasses that are siblings

Sometimes, two subclasses inherit the same parent class, and there is the same code between the subclasses. We can consider extracting the same code into the parent class, which is also called function up.
insert image description here
code show as below:

/**
 * 水果利润(两个互为兄弟的子类含有相同的表达式)
 *
 */
class Fruits {
    
    
    // 成本单价
    public double costPrices;

    // 出售单价
    public double prices;

    // 最小出货量
    public double minSaleableNum;
}

class Banana extends Fruits {
    
    
    public Banana(double costPrices, double prices, double minSaleableNum) {
    
    
        this.costPrices = costPrices;
        this.minSaleableNum = minSaleableNum;
        this.prices = prices;
    }

    public double profitMoney(int number) {
    
    
        return Math.max(0, number - minSaleableNum) * this.prices - this.costPrices * number;
    }
}
class Apple extends Fruits {
    
    
    public Apple(double costPrices, double prices, double minSaleableNum) {
    
    
        this.costPrices = costPrices;
        this.minSaleableNum = minSaleableNum;
        this.prices = prices;
    }

    public double profitMoney(int number) {
    
    
        return Math.max(0, number - minSaleableNum) * this.prices - this.costPrices * number;
    }
}

Use IDEA to move the same code up to the parent class:
1. Select the code that needs to be moved up
insert image description here
2. Shortcut Ctrl+Alt+Shift+T, select Pull Members UP
insert image description here
3. Click Refactor
insert image description here
4. After the current subclass is refactored, delete it manually The same methods in other subclasses.

2.3 Code duplication between different classes

Sometimes, the repeated code is not in the same class. In this case, the method is also refactored by extracting the method, but the refactored method is generally selected and defined as a static method.
insert image description here

Problem code:

class MonthJudgement {
    
    
    public boolean judgeMonth() {
    
    
        Long timeStamp = System.currentTimeMillis();  // 获取当前时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
        String month = date.split(" ")[0].split("-")[1];
        return "12".equals(month);
    }
}

class YearJudgement {
    
    
    public boolean judgeYear() {
    
    
        Long time = System.currentTimeMillis();  // 获取当前时间戳
        System.out.println("获得当前时间戳");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = dateFormat.format(new Date(Long.parseLong(String.valueOf(time))));
        return date.startsWith("2021");
    }
}

It can be analyzed that the logic of initialization time is the same in the two codes. These lines of code can be extracted as a static method. The steps are as follows:
1: Select the output code of YearJudgement and use the shortcut key to move it to the top, as follows Animation
insert image description here
2. Select the following code, and then use the shortcut key Ctrl+Alt+M
insert image description here
3. Select Declare static and public, cancel the annotation, and click refactor
insert image description here

4. Move the cursor to the static method just created in the class, then use the shortcut key Ctrl+Alt+Shift+T to select Extract Delegate
insert image description here
5. Enter the class name and the package name where the class is located in the new window
insert image description here
6. These codes will be used place, manually replaced with refactored static methods.

3. Summary of shortcut keys

insert image description here

Guess you like

Origin blog.csdn.net/qq_45171957/article/details/124414857