Eight schemes of if else code optimization

Optimization scheme 1: return in advance to remove unnecessary else

If the if else code block contains a return statement, you can consider returning in advance to eliminate the redundant else and make the code more elegant.

Before optimization:

if(condition){
    //doSomething
}else{
    return ;
}

After optimization:

if(!condition){
    return ;
}
//doSomething

Optimization scheme 2: use conditional ternary operators

Using conditional ternary operators can simplify some if else and make the code more concise and readable.

Before optimization:

int  price ;
if(condition){
    price = 80;
}else{
    price = 100;
}

After optimization:

int price = condition?80:100;

Optimization scheme 3: using enumeration

In some cases, enumeration can also be used to optimize if else logical branches. Personally, it can also be regarded as a table driven method.

Before optimization:

String OrderStatusDes;
if(orderStatus==0){
    OrderStatusDes ="Order not paid";
}else if(OrderStatus==1){
    OrderStatusDes ="Order paid";
}else if(OrderStatus==2){
   OrderStatusDes ="Shipped"; 
}
...

After optimization:

Define an enumeration first

: 
public enum OrderStatusEnum {
    UN_PAID(0,"Order not paid"),PAIDED(1,"Order paid"),SENDED(2,"Shipped"),;
    
    private int index;
    private String desc;

    public int getIndex() {
        return index;
    }

    public String getDesc() {
        return desc;
    }

    OrderStatusEnum(int index, String desc){
        this.index = index;
        this.desc =desc;
    }

    OrderStatusEnum of(int orderStatus) {
        for (OrderStatusEnum temp : OrderStatusEnum.values()) {
            if (temp.getIndex() == orderStatus) {
                return temp;
            }
        }
        return null;
    }
}


After enumeration, the above if else logical branches can be optimized into one line of code

String OrderStatusDes = OrderStatusEnum.0f(orderStatus).getDesc();

Optimization scheme 4: merge condition expression

If a series of conditions return the same result, they can be combined into a conditional expression to make the logic clearer.

Before optimization

 double getVipDiscount() {
        if(age<18){
            return 0.8;
        }
        if("Shenzhen".equals(city)){
            return 0.8;
        }
        if(isStudent){
            return 0.8;
        }
        //do somethig
    }

After optimization

 double getVipDiscount(){
        if(age<18|| "Shenzhen".equals(city)||isStudent){
            return 0.8;
        }
        //doSomthing
    }

Optimization scheme 5: use Optional

Sometimes there are many if else, which is caused by non empty judgment. At this time, you can use java8's Optional for optimization.

Before optimization:

String str = "jay@huaxiao";
if (str != null) {
    System.out.println(str);
} else {
    System.out.println("Null");
}

After optimization:

Optional<String> strOptional = Optional.of("jay@huaxiao");
strOptional.ifPresentOrElse(System.out::println, () -> System.out.println("Null"));

Optimization scheme 6: table driven method

Table driven method, also known as table driven, table driven method. Table driven method is a method that enables you to find information in a table without using many logical statements (if or Case) to find them. The following demo abstracts a map into a table and finds information in the map without unnecessary logic statements.

Before optimization:

if (param.equals(value1)) {
    doAction1(someParams);
} else if (param.equals(value2)) {
    doAction2(someParams);
} else if (param.equals(value3)) {
    doAction3(someParams);
}
// ...

After optimization:

Map<?, Function<?> action> actionMappings = new HashMap<>(); // Generic here? For the convenience of demonstration, it can actually be replaced with the type you need

// initialization
actionMappings.put(value1, (someParams) -> { doAction1(someParams)});
actionMappings.put(value2, (someParams) -> { doAction2(someParams)});
actionMappings.put(value3, (someParams) -> { doAction3(someParams)});

// Omit redundant logical statements
actionMappings.get(param).apply(someParams);

Optimization scheme 7: optimize the logical structure and make the normal process the backbone

Before optimization:

public double getAdjustedCapital(){
    if(_capital <= 0.0 ){
        return 0.0;
    }
    if(_intRate > 0 && _duration >0){
        return (_income / _duration) *ADJ_FACTOR;
    }
    return 0.0;
}

After optimization:

public double getAdjustedCapital(){
    if(_capital <= 0.0 ){
        return 0.0;
    }
    if(_intRate <= 0 || _duration <= 0){
        return 0.0;
    }
 
    return (_income / _duration) *ADJ_FACTOR;
}

Reverse the condition to make the exception exit first, and keep the normal process in the trunk process, which can make the code structure more clear.

Optimization scheme 8: strategic mode + factory method to eliminate if else

Suppose the demand is to process corresponding medal services according to different medal types. The following codes are available before optimization:

    String medalType = "guest";
    if ("guest".equals(medalType)) {
        System.out.println("Guest Medal");
     } else if ("vip".equals(medalType)) {
        System.out.println("Member Medal");
    } else if ("guard".equals(medalType)) {
        System.out.println("Show the guardian Medal");
    }
    ...

First, we abstract each conditional logic code block into a common interface, and the following codes can be obtained:

//Medal interface
public interface IMedalService {
    void showMedal();
}

We define the corresponding policy implementation class according to each logical condition, and the following code can be obtained:

//Guardian medal policy implementation class
public class GuardMedalServiceImpl implements IMedalService {
    @Override
    public void showMedal() {
        System.out.println("Show the guardian Medal");
    }
}
//Guest medal strategy implementation class
public class GuestMedalServiceImpl implements IMedalService {
    @Override
    public void showMedal() {
        System.out.println("Guest Medal");
    }
}
//VIP medal strategy implementation class
public class VipMedalServiceImpl implements IMedalService {
    @Override
    public void showMedal() {
        System.out.println("Member Medal");
    }
}

Next, we define the policy factory class to manage these medal implementation policy classes, as follows:

//Medal service industrial products
public class MedalServicesFactory {

    private static final Map<String, IMedalService> map = new HashMap<>();
    static {
        map.put("guard", new GuardMedalServiceImpl());
        map.put("vip", new VipMedalServiceImpl());
        map.put("guest", new GuestMedalServiceImpl());
    }
    public static IMedalService getMedalService(String medalType) {
        return map.get(medalType);
    }
}

After using the policy + factory mode, the code becomes much simpler, as follows:

public class Test {
    public static void main(String[] args) {
        String medalType = "guest";
        IMedalService medalService = MedalServicesFactory.getMedalService(medalType);
        medalService.showMedal();
    }
}

 

Tags: Java logistic regressive

Posted by DF7 on Mon, 30 May 2022 00:42:06 +0530