Several solutions for optimizing if-else code in Java

created at 09-15-2021 views: 2

Preface

Some status of the development system, such as order status: the database storage is numbers or letters, but it needs to display Chinese or English. Generally, if-else code is used to judge, but this judgment is relatively poor in readability and will also affect later maintenance. Prone to bugs. for example:
Assume the corresponding state of the relationship: 1:agree 2:refuse 3:finish

int status;
String statusStr = null;
if (status == 1) {
   status = "agree";
} else if (status == 2) {
   status = "refuse";
}else if(status == 3) {
    status = “finish”;
}

Option 1: Array

This is limited to obtaining letters or Chinese through numbers.
First set the array

String[] statusArray = {"","agree","refuse","finish"};

Get the value of the array by the position of the array

int status;
String statusStr =  statusArray[status];

Advantages: occupies less memory
Disadvantages: The state value can only be a number, but also need to consider the array out of bounds situation

Option 2: HashMap

Create and add map:

    private static final Map<Integer,String> map = new HashMap<>();

    static {
        map.put(1,"agree");
        map.put(2,"refuse");
        map.put(3,"finish");
    }

There are two ways to solve this, get value by key and get key by value,

Get value from key

Just use the get method. The key here is relative to the array solution and does not limit the type of key.

int status;
map.get(status);

Get key from value

Use map to traverse:

int status;
for(Map.Entry<Integer, String> vo : map.entrySet()){
     if (vo.getValue().equals(result)) {
           status = vo.getKey();
           break;
      }
}

Advantages: the status value does not limit the number
Disadvantages: take up a lot of space

option 3, enumeration

First define an enumeration class

public enum TestEum {

    agree(1,"agree"),
    refuse(2,"refuse");

    private int code;

    private String capation;

    TestEum(int code,String capation){
        this.code = code;
        this.capation = capation;
    }

    public int getCode() {
        return code;
    }

   public String getCapation() {
        return capation;
   }

   String of(int code){
        for (TestEum testEum : TestEum.values()) {
            if (testEum.getCode() == code) {
                return testEum.getCapation();
            }
        }
        return null;
    } 
}

With enumeration, the if-else code block can be optimized into one line of code

String statusStr = TestEum.of(status);

Summarize

If you get the description by number, just use an array.
If you get the number by description, you can use enumeration and HashMap.

created at:09-15-2021
edited at: 09-15-2021: