preface

If there are too many if-else’s in your code, it is difficult to read, difficult to maintain, and prone to bugs. Next, this article introduces eight ways to optimize if-else code.

Github.com/whx123/Java…

Optimization scheme 1: advance return, remove unnecessary else

If the if-else block contains a return statement, consider making the code more elegant by returning earlier and eliminating the else.

Before optimization:

if(condition){
    //doSomething
}else{
    return ;
}
Copy the code

After the optimization:

if(! Condition) {return; } / /doSomething
Copy the code

Optimization scheme two: the use of conditional ternary operators

Using conditional triadic operators can simplify some if-else’s, making the code cleaner and more readable.

Before optimization:

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

After the optimization:

int price = condition? 80-100;Copy the code

Optimization solution 3: Use enumerations

In some cases, the use of enumerations can also optimize the if-else branch of logic, which can also be seen as a table-driven approach to personal understanding.

Before optimization:

String OrderStatusDes;
if(orderStatus==0){
    OrderStatusDes ="Order unpaid";
}else if(OrderStatus==1){
    OrderStatusDes ="Order paid";
}else if(OrderStatus==2){
   OrderStatusDes ="Delivered"; }...Copy the code

After the optimization:

First define an enumeration

: public enum OrderStatusEnum {UN_PAID(0,"Order unpaid"),PAIDED(1,"Order paid"),SENDED(2,"Delivered"),;
    
    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) {
                returntemp; }}returnnull; }}Copy the code

With enumerations, the above if-else logic branch can be optimized to a single line of code

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

Optimization scheme 4: Merge conditional expressions

If you have a list of conditions that return the same result, you can combine them into a single 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){
            return0.8; } / /do somethig
    }
Copy the code

The optimized

 double getVipDiscount() {if(age<18|| "Shenzhen".equals(city)||isStudent){
            return0.8; } / /doSomthing
    }
Copy the code

Optimization solution 5: Use Optional

If -else if-else if-else if-else if-else if-else if-else

Before optimization:

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

After the optimization:

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

Optimization scheme six: table driven method

Table – driven method, also known as table – driven, table – driven method. The table-driven approach is a method that allows you to look up information in a table without having to use a lot of logical statements (if or Case) to find it. The following demo abstracts the map into a table and finds information in the map without unnecessary logical statements.

Before optimization:

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

After the optimization:

Map<? , Function<? > action> actionMappings = new HashMap<>(); // Generic? // Initialize actionMappings. Put (value1, (someParams) -> {doAction1(someParams)});
actionMappings.put(value2, (someParams) -> { doAction2(someParams)});
actionMappings.put(value3, (someParams) -> { doAction3(someParams)}); Actionmingle.get (param).apply(someParams); // Omit the logic statement actionMingle.get (param).apply(someParams);Copy the code

Optimization scheme 7: Optimize the logical structure and let the normal process go through the trunk

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;
}
Copy the code

After the optimization:

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

Reversing the condition so that the exception exits first and the normal flow remains in the trunk can make the code structure clearer.

Optimization scheme eight: strategy mode + factory method to eliminate if else

Assume that the requirement is to process corresponding medal services according to different medal types. The following code is provided before optimization:

    String medalType = "guest";
    if ("guest".equals(medalType)) {
        System.out.println("Guest Medal");
     } else if ("vip".equals(medalType)) {
        System.out.println("Member's Medal");
    } else if ("guard".equals(medalType)) {
        System.out.println("Show the Guard medal."); }...Copy the code

First, we abstracted each block of conditional logic code into a common interface, resulting in the following code:

Public interface IMedalService {void showMedal(); }Copy the code

According to each logical condition, we define the corresponding policy implementation class, the following code can be obtained:

Public class GuardMedalServiceImpl implements IMedalService {@override public voidshowMedal() {
        System.out.println("Show the Guard medal."); }} public class GuestMedalServiceImpl implements IMedalService {@override public voidshowMedal() {
        System.out.println("Guest Medal"); }} public class implements IMedalService {@override public voidshowMedal() {
        System.out.println("Member's Medal"); }}Copy the code

Next, we redefine the policy factory class that will manage these MEDALS to implement the policy class as follows:

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) {
        returnmap.get(medalType); }}Copy the code

After using the policy + factory pattern, the code becomes much cleaner, as follows:

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

Reference and Thanks

  • How to reassemble if-else code into high-quality code
  • How to “kill” if… else

Personal public Account

  • If you think it’s good, please give me a thumbs up and follow me. Thank you
  • At the same time, I am looking forward to friends can pay attention to my public number, and slowly introduce better dry goods ~ xi xi
  • Github: github.com/whx123/Java…