Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize if/ else code

2025-03-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to optimize if/ else code". In daily operation, I believe many people have doubts about how to optimize if/ else code. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to optimize if/ else code". Next, please follow the editor to study!

Why do we write all the code in if-else?

Programmers must have experienced such a scenario: at the beginning, the code written by themselves is very concise, the logic is clear, the function is simplified, and there is no if-else, but with the continuous improvement of the code logic and the ever-changing business: for example, you need to judge the type and value of the input parameters; here, you need to determine whether the object executes different processes for different types of null;.

Landing to the specific implementation can only constantly add if-else to deal with, gradually, the code becomes larger and larger, the function is getting longer and longer, the number of file lines is also rapidly breaking through thousands of lines, maintenance is becoming more and more difficult, and basically reached a state that is difficult to maintain in the later stage.

Although we are very reluctant to write a full screen of if-else code, but logic is the need for special judgment, very desperate, but there is no way to avoid it.

In fact, looking back at your code, writing if-else is nothing more than two scenarios: exception logic handling and different state handling.

The main difference between the two is that exception logic processing indicates that only one branch is a normal process, while all branches in different states are normal processes.

How do you understand it? For example:

1 example 1: exception logic handling example 2Object obj = getObj (); 3if (obj! = null) {4 / / do something 5} else 6 / / do something 7} 8 9 move / example 2: state handling example 10Object obj = getObj (); 11if (obj.getType = = 1) {12 / / do something13} else if (obj.getType = = 2) {14 / / do something15} else {16 / do something17}

The first example if (obj! = null) is exception handling, which is the judgment of code robustness. Only in if is the normal handling flow, and the else branch is the error handling flow; while the second example belongs to the normal process of the business, regardless of whether type equals 1d2 or other situations. The methods of refactoring are also different in these two cases.

What are the disadvantages of too much code if-else?

The disadvantage is quite obvious: the biggest problem is that the code logic is complex, the maintainability is poor, and it is very easy to cause bug. If you use if-else, it shows that the if branch and the else branch attach equal importance, but in most cases this is not the case, which can easily lead to misunderstanding and difficulty in understanding.

Is there a good way to optimize it? How to reconstruct?

There must be a way. When refactoring if-else, you have a principle in mind all the time:

Keep the normal process code at the outermost layer as much as possible.

It means that when you can write if-else statements, you must try to keep the trunk code as normal as possible to avoid being too deeply nested.

The means to achieve are: reducing nesting, removing temporary variables, judging the inverse of conditions, merging conditional expressions and so on.

Here are some examples to illustrate these refactoring methods:

Example 1 of exception logic processing reconstruction method

Before 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 1011 / / do somethig12}

After refactoring:

1double disablityAmount () {2 if (_ seniority)

< 2 || _monthsDisabled >

12 | | _ isPartTime) 3 return 0bot 45 / / do somethig6}

The refactoring technique here is called merging conditional expressions: if there are a series of conditional tests that all get the same results, merge the result tests into a single conditional expression.

This refactoring technique is simple and easy to understand, and the effect is also very obvious. it can effectively reduce the number of if statements and reduce the amount of code, which is logically easier to understand.

Example 2 of exception logic processing reconstruction method

Before 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}

After refactoring:

1double getPayAmount () {2 if (_ isDead) 3 return deadAmount (); 4 5 if (_ isSeparated) 6 return separatedAmount (); 7 8 if (_ isRetired) 9 return retiredAmount (); 1011 return normalPayAmount (); 12}

How's it going? Comparing the two versions, you will find that the refactored version is logical, concise and easy to understand.

What's the difference between it and before refactoring?

The biggest difference is to reduce if-else nesting. As you can see, the deepest nesting of the original version of if-else has three layers, and it seems that there are so many logical branches that almost all of them will be stunned. In fact, think carefully about the if-else in the nest and the outermost layer is not related, you can extract the top level.

The number of if-else has not changed, but the logic is clear and clear at a glance.

Another reconstruction point is that the result temporary variable is abolished and returned directly by return. The benefits are also obvious to end the process directly and shorten the exception branch process. The original practice first assigns a value to result and then unifies the return, so it is not clear which function returns the value of the final return, which adds a layer of difficulty to understanding.

Summarize the main points of refactoring: if if-else nesting is not relevant, extract it directly to the first layer, and be sure to avoid too deep logical nesting. Minimize temporary variables and use return to return directly.

Example 3 of exception logic processing reconstruction method

Before refactoring:

1public double getAdjustedCapital () {2 double result = 0.0x 3 if (_ capital > 0.0) {4 if (_ intRate > 0 & & _ duration > 0) {5 resutl = (_ income / _ duration) * ADJ_FACTOR;6} 7} 8 return result;9}

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

1public double getAdjustedCapital () {2 if (_ capital 0 & & _ duration > 0) {6 return (_ income / _ duration) * ADJ_FACTOR;7} 8 return 0.0ter9}

After refactoring, it is not enough, because the main statement (_ income / _ duration) * ADJ_FACTOR; is inside the if, not at the outermost layer. According to the optimization principle (keeping the normal process code at the outermost layer as much as possible), you can continue the refactoring:

1public double getAdjustedCapital () {2 if (_ capital)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report