Why do we always write if-else code?

Programmers must have experienced such scenarios: at the beginning, their code is very simple, with clear logic and simplified functions, without an if-else, which can be improved with the continuous improvement of code logic and the rapid change of business: for example, the type and value of input parameters need to be judged; I’m going to check whether the object is null; Different types perform different processes.

When it comes to the concrete implementation, we can only keep adding if-else to deal with it. Gradually, the code becomes bigger and bigger, the function becomes longer and longer, the number of lines in the file quickly breaks through thousands of lines, and the maintenance becomes more and more difficult, and basically reaches a state of difficult maintenance in the later stage.

Although we are reluctant to write code with a screen full of if-else, the logic requires special judgment, desperation, but there is no way to avoid it.

In fact, if you look back at your own code, there are only two scenarios for writing if-else: exception logic handling and different state handling.

The main difference between the two is that exception logic indicates that only one branch is normal flow, while all branches are normal flow for different state processing. How to understand? Here’s an example:

2Object obj = getObj(); 3if (obj ! = null) {4 //do something 5}else{6 //do something 7} 8 9 11if (obj.getType == 1) { 12 //do something 13}else if (obj.getType == 2) { 14 //do something 15}else{ 16 //do something 17}Copy the code

The first example is if (obj! = null) is the exception handling, is the code robustness judgment, only if is the normal processing flow, else branch is the error processing flow; The second example, whether type equals 1,2 or otherwise, is the normal flow of business. The refactoring approach is also different in both cases.

What’s the downside of too much if-else code?

The disadvantages are quite obvious: the biggest problem is that the code logic is complex, the maintainability is poor, and it is very bug prone. If if-else is used, it indicates that the if branch and the else branch are equally valued, but this is not the case in most cases, which can lead to misunderstanding and difficulty in understanding.

Is there a good way to optimize? How do you refactor?

There must be a way. When refactoring if-else, keep one rule in mind at all times: keep normal flow code in the outermost layer as much as possible.

When you can write if-else statements, try to keep the trunk as normal as possible and avoid too much nesting.

The implementation methods include: reducing nesting, removing temporary variables, reverse judgment of conditions, merging conditional expressions, etc. Internet architects can get a full set of Java architecture videos. Here are a few examples of these refactoring methods:

Example 1 of abnormal logic processing reconstruction method

Refactoring:

 1double disablityAmount(){
 2    if(_seniority < 2)
 3        return 0;
 4
 5    if(_monthsDisabled > 12)
 6        return 0;
 7
 8    if(_isPartTime)
 9        return 0;
10
11    //do somethig
12}
Copy the code

After the refactoring:

1double disablityAmount(){
2    if(_seniority < 2 || _monthsDisabled > 12 || _isPartTime)
3        return 0;
4
5    //do somethig
6}
Copy the code

The refactoring technique here is called merging conditional expressions: If you have a series of conditional tests that all yield the same result, merge those result tests into a single conditional expression.

This refactoring is easy to understand and the results are obvious, effectively reducing the number of if statements, reducing the amount of code and making it logically easier to understand.

Example 2 of abnormal logic processing reconstruction method

Refactoring:

 1double getPayAmount(){
 2    double result;
 3    if(_isDead) {
 4        result = deadAmount();
 5    }else{
 6        if(_isSeparated){
 7            result = separatedAmount();
 8        }
 9        else{
10            if(_isRetired){
11                result = retiredAmount();
12            else{
13                result = normalPayAmount();
14            }
15        }
16    }
17    return result;
18}
Copy the code

After the refactoring:

 1double getPayAmount(){
 2    if(_isDead)
 3        return deadAmount();
 4
 5    if(_isSeparated)
 6        return separatedAmount();
 7
 8    if(_isRetired)
 9        return retiredAmount();
10
11    return normalPayAmount();
12}
Copy the code

How’s that? Comparing the two versions, you will find that the reconstructed version is logical and simple.

What’s the difference from pre-refactoring?

The biggest difference is the reduction of if-else nesting. As you can see, the original version of if-else has three layers of nesting at its deepest level, and it looks like there are so many branches that you can almost get confused if you enter it. In fact, if you think about it, the nested if-else has no relation to the outermost layer, so you can extract the outermost layer.

If else, the number of if-else is the same, but the logic is clear.

Another refactoring point was to do away with the result temporary variable and return directly. The benefits are also obvious: end the process directly and shorten the abnormal branch process. In the original practice, the value is assigned to result and then unified return, so it is not clear which function returns the value of the last return, which adds another layer of difficulty to understand.

Summary of refactoring points: If if-else nesting has no correlation, extract directly to the first layer, be sure to avoid logical nesting too deep. Minimize the use of temporary variables to return directly.

Example 3 of abnormal logic processing reconstruction method

Refactoring:

1public getAdjustedCapital(){2 double result = 0.0; 3 if(_capital > 0.0){4 if(_intRate >0 &&_duration >0){5 resutl = (_income / _duration) *ADJ_FACTOR; 6 } 7 } 8 return result; 9}Copy the code

The first step is to reduce nesting and remove temporary variables using the first trick:

1public getAdjustedCapital(){2 if(_adjustedcapital <= 0.0){3 return adjustedCapital (); 4 } 5 if(_intRate > 0 && _duration >0){ 6 return (_income / _duration) *ADJ_FACTOR; 7} 8 return 0.0; 9}Copy the code

This refactoring is not enough because the main statement (_income / _duration) *ADJ_FACTOR; Within if, but not at the outermost layer, refactoring can continue according to optimization principles (keeping normal flow code at the outermost layer as much as possible) :

1public getAdjustedCapital(){2 if(_adjustedcapital <= 0.0){3 return adjustedCapital (); 5 if 4} (_intRate < = 0 | | _duration < = 0) {6 return 0.0; 7 } 8 9 return (_income / _duration) *ADJ_FACTOR; 10}Copy the code

This is good code style, clear logic, clear at a glance, no if-else nested incomprehensible flow.

The refactoring method used here is to reverse the condition so that the exception exits first, leaving the normal flow in the main flow.

Example 4 of abnormal logic processing reconstruction method

Refactoring:

Public ArrayList<Student> getStudents(int uid){3 ArrayList<Student> result = new ArrayList<Student>(); 4 Student stu = getStudentByUid(uid); 5 if (stu ! = null) { 6 Teacher teacher = stu.getTeacher(); 7 if(teacher ! = null){ 8 ArrayList<Student> students = teacher.getStudents(); 9 if(students ! = null){ 10 for(Student student : students){ 11 if(student.getAge() > = 18 && student.getGender() == MALE){ 12 result.add(student); 13} 14} 15}else {16 logger.error(" Failed to get student list "); 17} 18}else {19 logger.error(" Failed to get teacher info "); 20} 21} else {22 logger.error(" Failed to get student information "); 23 } 24 return result; 25}Copy the code

Typical “arrow” code, the biggest problem is too deep nesting, the solution is to exit the exception condition first, keep the trunk flow is the core flow:

After the refactoring:

Public ArrayList<Student> getStudents(int uid){3 ArrayList<Student> result = new ArrayList<Student>(); 4 Student stu = getStudentByUid(uid); 5 if (stu == null) {6 logger.error(" failed to get student information "); 7 return result; 8 } 9 10 Teacher teacher = stu.getTeacher(); 11 if(teacher == null){12 logger.error(" failed to get teacher information "); 13 return result; 14 } 15 16 ArrayList<Student> students = teacher.getStudents(); 17 if(students == null){18 logger.error(" Failed to get student list "); 19 return result; 20 } 21 22 for(Student student : students){ 23 if(student.getAge() > 18 && student.getGender() == MALE){ 24 result.add(student); 25 } 26 } 27 return result; 28}Copy the code

Example 1 of state-processing reconstruction method

Refactoring:

1double getPayAmount(){ 2 Object obj = getObj(); 3 double money = 0; 4 if (obj.getType == 1) { 5 ObjectA objA = obj.getObjectA(); 6 money = objA.getMoney()*obj.getNormalMoneryA(); 7 } 8 else if (obj.getType == 2) { 9 ObjectB objB = obj.getObjectB(); 10 money = objB.getMoney()*obj.getNormalMoneryB()+1000; 12 11}}Copy the code

After the refactoring:

 1double getPayAmount(){
 2    Object obj = getObj();
 3    if (obj.getType == 1) {
 4        return getType1Money(obj);
 5    }
 6    else if (obj.getType == 2) {
 7        return getType2Money(obj);
 8    }
 9}
10
11double getType1Money(Object obj){
12    ObjectA objA = obj.getObjectA();
13    return objA.getMoney()*obj.getNormalMoneryA();
14}
15
16double getType2Money(Object obj){
17    ObjectB objB = obj.getObjectB();
18    return objB.getMoney()*obj.getNormalMoneryB()+1000;
19}
Copy the code

The refactoring method used here is to wrap the if-else code into a common function. The function has the advantage of masking the internal implementation and shortening the code for the if-else branch. The code structure and logical clear, can be seen in each condition to do the function.

Example 2 of state-processing reconstruction method

An elegant way to do state-handling code is to replace conditional expressions with polymorphism (refactoring recommends that).

You have a conditional expression that selects different behaviors based on the object type. Put each branch of this expression into an overriding function in a subclass, and then declare the original function as an abstract function.

Refactoring:

 1double getSpeed(){
 2    switch(_type){
 3        case EUROPEAN:
 4            return getBaseSpeed();
 5        case AFRICAN:
 6            return getBaseSpeed()-getLoadFactor()*_numberOfCoconuts;
 7        case NORWEGIAN_BLUE:
 8            return (_isNailed)?0:getBaseSpeed(_voltage);
 9    }
10}
Copy the code

After the refactoring:

1class Bird{ 2 abstract double getSpeed(); 3} 4 5class European extends Bird{ 6 double getSpeed(){ 7 return getBaseSpeed(); 8 } 9} 10 11class African extends Bird{ 12 double getSpeed(){ 13 return getBaseSpeed()-getLoadFactor()*_numberOfCoconuts; 14 } 15} 16 17class NorwegianBlue extends Bird{ 18 double getSpeed(){ 19 return (_isNailed)? 0:getBaseSpeed(_voltage); 20}} 21Copy the code

As you can see, the if-else is gone with polymorphism, but it takes a lot of work to modify the original code using polymorphism. It is best to use polymorphism from the beginning of design. Internet architects can get architecture videos.

conclusion

If-else code is the easiest code for any programmer to write, and it’s also the easiest code to break, resulting in a bunch of hard-to-maintain and illogical code if you don’t pay attention to it.

One principle for conditional code refactoring:

As much as possible, keep the normal process code in the outermost layer and the trunk as the normal core process. To maintain this principle, merging conditional expressions can effectively reduce the number of if statements; Reducing nesting reduces deep logic; The abnormal condition first exits and the trunk flow becomes the normal flow.

There are two methods for state-processing reconstruction: one is to encapsulate operations in different states into functions with short if-else lines of code; The other method uses object-oriented polymorphism to eliminate conditional judgment directly.

Now take a look at your code, what typical mistakes you made, and use these refactoring methods to refactor your code!

Original link: blog.csdn.net/qq\_3544067…