A few tips to optimize code

Foreword

Recently read "Reconstruction - to improve the design of existing code" This book summarizes the optimized code a few tips to share with you.

Rendering function (function properly extract small)

definition

Refining function is a piece of code into a separate function, and let the function name to explain the purpose of the function.

Too long a period of a function or a comment to make people understand the need to use the code, you can consider it to be cut into a functional unit definite function , and define clear and brief function name , this will make the code more elegant.

Examples of optimization

Refining before 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);
    }
复制代码

After extraction function:

Above that code, it can be pumped into the print banner, calculate totalAmount, print details three functions of a single function, 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);
    }

复制代码

Inline function (function properly remove excess)

definition

Inline function is to insert a function call point function in the body, then remove the function.

In the previous section of the refining function code optimization approach to short and clear the small function proud. But then, small functions are not better it? Certainly not you, sometimes you encounter some function, its internal code name and function the same clear, this time you can consider it an inline function to optimize a little longer.

Examples of optimization

Before inline function

    int getRating(){
        return moreThanFiveDeliveries() ? 2 : 1;
    }
    boolean moreThanFiveDeliveries(){
        return numberOfLateDeliveries >5;
    }
复制代码

After inline function

  int getRating(){
        return numberOfLateDeliveries >5 ? 2 : 1;
 }
复制代码

Inline temporary variables (temporary variables removing excess)

definition

Inline temporary variables all reference to this variable action and replaced it with the expression assignment.

Examples of optimization

Before Inline temporary variables

double basePice = anOrder.basePrice();
return basePice >888;
复制代码

After inline temporary variables

 return anOrder.basePrice() >888;
复制代码

The introduction of explanatory variables

definition

Introduction of explanatory variables is the result of a complex expression (or part) is placed in a temporary variable expression in order to explain the use of the variable name.

Some expressions can be very complex difficult to read, in this case, the temporary variables that can help you break down the expression into readable form.

In more complex conditional logic, you can use the introduction of explanatory variables each condition clause extracted to a temporary variable to explain the significance of good naming the corresponding condition clause.

Examples of optimization

Before the introduction of explanatory variables

if ((platform.toUpperCase().indexOf("mac") > -1) &&
    (brower.toUpperCase().indexOf("ie") > -1) &&
    wasInitializes() && resize > 0) {
        ......
    }
复制代码

Following the introduction of 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) {
    ......
}
复制代码

To replace the literal magic number

definition

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

The so-called magic number refers to has a special meaning, but can not clearly show figures in this sense. If you need to refer to the same logical number of different locations , every time the digit to be modified, will be particularly troublesome because the leak is likely to change. The literal magic number of substitutions can solve this headache problem.

Examples of optimization

Prior to replace literal magic number

double getDiscountPrice(double price){
       return price * 0.88;
 }
复制代码

After the magic number to replace literals

 static final double DISCOUNT_CONSTANT=0.88;
 
 double getDiscountPrice(double price){
     return price * DISCOUNT_CONSTANT;
 }
复制代码

Alternatively a multi-state switch statement

definition

Alternatively a multi-state switch statement is to use the object-oriented Java polymorphic features, the switch statement used to replace state mode.

Examples of optimization

Polymorphic replaced with a switch statement before

 int getArea() {
        switch (shape){
        case SHAPE.CIRCLE:
        return 3.14 * _r * _r; break;
        case SHAPE.RECTANGEL;
        return width *,heigth;
        }
    }
复制代码

After replacement with a switch statement Polymorphism

 class Shape {
        int getArea(){};
    }

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

    class Rectangel extends Shape {
        int getArea() {
            return width * heigth;
        }
    }
复制代码

The excess of the parameter object

definition

The excess of the parameter object is to excessive parameter relates to a packaged into object by reference.

A method when there are too many mass participation, that is hard to read and difficult to maintain. Especially for dubbo remote call these methods, if there are too many parameters, increase or decrease a parameter, you must modify the interface, really pit. If these parameters are packaged into an object, it is well maintained, do not modify the interface.

Examples of optimization

The parameter object before too much of:

public int register(String username,String password,Integer age,String phone);
复制代码

After the excess of the parameter object:

 public int register(RegisterForm from );
 
 class RegisterForm{
     private String username;
     private String password;
     private Integer age;
     private String phone;
 }
复制代码

Reference and thanks

  • "Reconstruction - to improve the design of existing code."

Personal Public Number

  • If you are a love of learning boy, I can focus on the public number, learning together discussion.
  • What if you feel that this article is not the right place, can comment, I can also concerned about the number of public, private chat me, we will study together progress Kazakhstan.

Guess you like

Origin juejin.im/post/5d36dc86518825680e457575