if...else code optimization

Keywords: Programming

There are too many if else in the coding. On the one hand, the original design didn't pay attention to it; on the other hand, it may be because of the changing requirements. But a lot of if else in the code knows that this situation is not good, so let's talk about how to optimize this situation

if(Condition 1){
    ....
}else if(Condition 2){
    ....
}else if(Condition 3){
    ....
}else{
    ....
}

1. table drive

Table driven is to obtain values by looking up tables

private static Map<Status, Function<Integer, Integer>> conditions;
static {
    conditions = new HashMap<>();
    conditions.put(Status.CONDITION1,(t)->{
        return t+1;
    });
    conditions.put(Status.CONDITION2,(t)->{
        return t+2;
    });
}

@Test
public void test(){
    Integer apply = conditions.get(Status.CONDITION1).apply(1);
    System.out.println(apply);
}

enum Status{
    CONDITION1,CONDITION2;
}

2. Responsibility chain mode

When the judging conditions are complex and changeable, the above driving table cannot be used.
There are many scenarios used in the responsibility chain, such as Filter and Interceptor.

abstract class Handler {

    protected Handler next;

    public void setNext(Handler next) { // Set next processor
        this.next = next;
    }

    public abstract void handlerRequest(int request); // Request processing logic
}

class ConcreteHandler1 extends Handler {
    @Override
    public void handlerRequest(int request) {
        if (request >= 0) {
            System.out.println("request >= 0");
        } else {
            // If the conditions are not met, proceed to the next time
            next.handlerRequest(request); // Send request to next bit
        }
    }
}
class ConcreteHandler2 extends Handler {
    @Override
    public void handlerRequest(int request) {
        if (request >= 10) {
            System.out.println("request >= 10");
        } else {
            // If the conditions are not met, proceed to the next time
            next.handlerRequest(request); // Send request to next bit
        }
    }
}

public class TestHandler {
    public static void main(String[] args) {
        Handler handler1 = new ConcreteHandler1();
        Handler handler2 = new ConcreteHandler2();
        // Setting up the next step of the responsibility chain
        handler1.setNext(handler2);
        handler1.handlerRequest(8);
    }
}

Posted by Ruchi on Sun, 05 Apr 2020 01:54:18 -0700