preface

I recently read the book refactoring – Improving the Design of Existing Code, and summarized some tips for optimizing your code.

Extract function (extract small function appropriately)

define

Refining a function is putting a piece of code into a separate function and letting the function name explain what the function does.

If a function is too long or a piece of code needs comments to understand its purpose, consider breaking it up into functional units and defining short, clear function names. This makes the code more elegant.

Optimization example

Before extracting the function:

    private String name;
    private Vector<Order> orders = new Vector<Order>();

    public void printOwing() {
        //print banner
        System.out.println("* * * * * * * * * * * * * * * *");
        System.out.println("*****customer Owes *****");
        System.out.println("* * * * * * * * * * * * * * * *");

        //calculate totalAmount
        Enumeration env = orders.elements();
        double totalAmount = 0.0;
        while(env.hasMoreElements()) { Order order = (Order) env.nextElement(); totalAmount += order.getAmout(); } / /print details
        System.out.println("name:" + name);
        System.out.println("amount:" + totalAmount);
    }
Copy the code

After refining the function:

The above code can be extracted into a single function of print banner, calculate totalAmount and print details, as follows:

    private String name;
    private Vector<Order> orders = new Vector<Order>();

    public void printOwing() {
        
        //print banner
        printBanner();
        //calculate totalAmount
        double totalAmount = getTotalAmount();
        //print details
        printDetail(totalAmount);
    }

    void printBanner(){
        System.out.println("* * * * * * * * * * * * * * * *");
        System.out.println("*****customer Owes *****");
        System.out.println("* * * * * * * * * * * * * * * *");
    }

    double getTotalAmount(){
        Enumeration env = orders.elements();
        double totalAmount = 0.0;
        while (env.hasMoreElements()) {
            Order order = (Order) env.nextElement();
            totalAmount += order.getAmout();
        }
        return totalAmount;
    }

    void printDetail(double totalAmount){
        System.out.println("name:" + name);
        System.out.println("amount:" + totalAmount);
    }

Copy the code

Inline functions (remove redundant functions appropriately)

define

An inline function is one that inserts the function body at the function call point and then removes the function.

The previous section introduced the refinement of function code optimization, which prides itself on being short and clear with small functions. But isn’t the more the better? No, sometimes you’ll run into functions whose internal code is as clear as the function’s name, and you might want to optimize inline functions.

Optimization example

Before the function is inlined

    int getRating() {returnmoreThanFiveDeliveries() ? 2:1; } booleanmoreThanFiveDeliveries() {return numberOfLateDeliveries >5;
    }
Copy the code

After the function is inlined

  int getRating() {returnnumberOfLateDeliveries >5 ? 2:1; }Copy the code

Inline temporary variables (remove excess temporary variables)

define

An inline temporary variable replaces all references to the variable with the expression to which it was assigned.

Optimization example

Inlining temporary variables before

double basePice = anOrder.basePrice();
return basePice >888;
Copy the code

After inlining temporary variables

 return anOrder.basePrice() >888;
Copy the code

Introduce explanatory variables

define

To introduce an explanatory variable is to put the result of that complex expression (or part of it) into a temporary variable whose name explains the expression’s purpose.

Some expressions can be too complex to read, in which case temporary variables can help you break the expression into a readable form.

In more complex conditional logic, you can extract each conditional clause by introducing explanatory variables, using a well-named temporary variable to explain the meaning of the corresponding conditional clause.

Optimization example

Before introducing explanatory variables

if ((platform.toUpperCase().indexOf("mac") > -1) &&
    (brower.toUpperCase().indexOf("ie") > -1) &&
    wasInitializes() && resize > 0) {
        ......
    }
Copy the code

After introducing explanatory variables

final boolean isMacOS = platform.toUpperCase().indexOf("mac") > 1; final boolean isIEBrowser = brower.toUpperCase().indexOf("ie") > 1; final boolean wasResized = resize > 0;if (isMacOS && isIEBrowser && wasInitializes() && wasResized) {
    ......
}
Copy the code

Replace magic numbers with literal constants

define

Create a constant, name it according to its meaning, and replace the literal value above with this constant.

Magic numbers are numbers that have a special meaning but do not express that meaning explicitly. If you need to refer to the same logical number in different places, it can be a real headache whenever the number has to be changed, because it will probably be missed. Replacing magic numbers with literal constants solves this headache.

Optimization example

Before replacing magic numbers with literal constants

double getDiscountPrice(double price){
       returnPrice * 0.88; }Copy the code

After replacing magic numbers with literal constants

The static final double DISCOUNT_CONSTANT = 0.88; double getDiscountPrice(double price){return price * DISCOUNT_CONSTANT;
 }
Copy the code

Replace switch statements with polymorphisms

define

Replacing switch statements with polymorphism takes advantage of Java’s object-oriented polymorphism by replacing switch statements with state mode.

Optimization example

Replace the switch statement before polymorphism

 int getArea() {
        switch (shape){
        case SHAPE.CIRCLE:
        return 3.14 * _r * _r; break;
        case SHAPE.RECTANGEL;
        returnwidth *,heigth; }}Copy the code

After replacing the switch statement with polymorphism

 class Shape {
        int getArea() {}; } class Circle extends Shape { intgetArea() {
            return 3.14 * r * r; 
        }
    }

    class Rectangel extends Shape {
        int getArea() {
            returnwidth * heigth; }}Copy the code

Objectification of too many parameters

define

Objectification of too many parameters encapsulates too many parameters as one object parameter.

When a method has too many pass-throughs, it is both difficult to read and difficult to maintain. Especially for dubbo remote calls to these methods, if there are too many parameters, add or subtract a parameter, have to modify the interface, really a hole. If these parameters are encapsulated as an object, they are easy to maintain without modifying the interface.

Optimization example

Before objectifying too many arguments:

public int register(String username,String password,Integer age,String phone);
Copy the code

After objectifying too many arguments:

public int register(RegisterForm from ); Class RegisterForm{private String username; Private String password; Private Integer age; Private String phone; }Copy the code

Reference and thanks

  • Refactoring – Improving the Design of Existing Code

Personal public account

  • If you are a good boy who loves learning, you can follow my public account and study and discuss with me.
  • If you feel that this article is not correct, you can comment, you can also follow my public account, private chat me, we learn and progress together.