Refactoring-improved the design of existing code: Simplified conditional expressions (7)

Source: Internet
Author: User
Simplified condition expression 1. Decompose Conditional decomposition condition expression

You have a complex conditional statement.Separate independent functions from the if, then, and else sections..


Among programs, complex conditional logic is one of the most frequent locations that lead to increased complexity. You must write code to check different condition branches and perform different tasks based on different branches. Then, you will soon get a fairly long function. Large functions will reduce the readability of the Code, while conditional logic will make the code more difficult to read. In a function with complex conditional logic, the Code (including the code that checks the conditional branch and the code that actually implements the function) will tell you what happened, when you often cannot figure out why this happens, it means that the readability of the Code is indeed greatly reduced.

Like any large block header code, you can break it into multiple independent functions and name new functions according to the purpose of each small block code, change the code in the original function to call the new function to clearly express your intention. For Conditional logic, splitting each branch condition into a new function brings you more benefits: it can highlight the conditional logic and clearly show the role of each branch, highlight the cause of each branch.

2. Merge lidate Conditional Expression merge condition Expression

You have a series of conditional tests and get the same results.Combine these tests into a conditional expression and extract the conditional expression into an independent function.


Sometimes you will find a series of condition checks: The check conditions are different, but the final behavior is consistent. If this is the case, combine them into a conditional expression using "logical or" and "logical and.

There are two important reasons for merging conditional expressions. First, the combined condition code will tell you that "there is actually only one condition check, but there are multiple parallel conditions that need to be checked", so that the purpose of this check is clearer. Of course, the original and Merged Code have the same results, but the original code sends the message "here there are some independent conditional tests, they happen only at the same time ". Second, this Refactoring can often be used for you to use Extract
Method. Refining the check condition into an independent function is very useful for clarifying the meaning of the Code, because it replaces the statement describing "what is done" with "why ".

The reason for merging condition statements also points out the reason for not merging: If you think that these condition checks are indeed independent of each other and should not be considered as the same check, then do not use this reconstruction. In this case, your code clearly expresses your meaning.

3. Merge lodate Duplicate Conditional Fragments to merge Duplicate condition Fragments

Each branch of the conditional expression has the same piece of code.Move the duplicate code out of the conditional expression.


All branches of a set of conditional expressions execute the same code segment. You should move this code out of the expression. In this way, the code can more clearly indicate what changes with the condition and what remains unchanged.

4. Remove Control Flag

In a series of boolean expressions, a variable carries a "control flag.

Replace the control mark with a break or return statement.



In a series of condition expressions, we often see the control mark used to determine when to stop the condition check. The trouble caused by such a tag exceeds the convenience it brings. People use such control labels because structured programming principles tell them that each subroutine can have only one entry and exit. The "Single Exit" principle will allow you to add annoying control labels to your code, greatly reducing the readability of conditional expressions. This is why the programming language provides break and continue statements: use them to jump out of complicated conditional statements. The effect of removing the control mark is often surprising: the true purpose of the Condition Statement is much clearer.

5. Replace Nested Conditional with Guard Clauses Replace Nested condition expressions with Guard statements

The conditional logic in the function makes it difficult for people to see the normal execution path.Use the Wei statement to show all special cases.


Conditional expressions are usually expressed in two forms. 1. All branches are normal. Second, only one of the answers provided by the conditional expressions is normal, and others are uncommon.

These two types of conditional expressions have different purposes. If the two branches are normal, you should use the form such as if ..... Else ..... If a condition is extremely rare, it should be checked separately and immediately returned from the function when the condition is true. Such a separate check is often called a "Health statement ".

Replace Nested Conditional with Guard Clauses (Replace Nested Conditional expressions with Guard statements) is the essence of giving a branch special attention. It tells readers that this situation is rare. if it does happen, perform necessary sorting and exit.

The idea that "each function can have only one entry and one exit" is deeply rooted in the minds of some programmers. Today's programming languages force each function to have only one entry. As for the Single Exit rule, it is not so useful. Keeping the code clear is the key: if a single exit makes the function clearer and easier to read, a single exit is used; otherwise, this is not necessary.

(Wei statements split complex condition expressions into multiple condition expressions. For example, a complicated expression is nested with several layers of if-then-else statements, convert multiple if statements to implement its logic. These multiple if statements are Wei statements .)

6. Replace Conditional with Polymorphism Replace the Conditional expression with Polymorphism

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


The most fundamental benefit of polymorphism is that if you need to take different behaviors based on different types of objects, polymorphism makes it unnecessary to write certain conditional expressions.

Because of the polymorphism, you will find that "switch statement of type" and "if-then-else statement based on type name" rarely appear in object-oriented programs.

Polymorphism can bring many benefits to you. If the same set of conditional expressions appear in many places of the program, the biggest benefit is the use of polymorphism. When using conditional expressions, if you want to add a new type, you must search for and update all conditional expressions. However, if polymorphism is used, you only need to create a new subclass and provide the appropriate functions in it. Class users do not need to understand this subclass, which greatly reduces the dependency between various parts of the system and makes the system upgrade easier.

7. Introduce Null Object introduces Null Object

You need to check whether an object is null again and again.Replace null with a null object.


The most fundamental benefit of polymorphism is that you don't have to ask the object "What type are you?" and then call an action of the object based on the answer-you just need to call this action, all other polymorphism mechanisms will be arranged for you. When the content of a field is null, polymorphism can play another inintuitive purpose.


8. Introduce Assertion introduces assertions

A piece of code needs to make some assumptions about the program status.This assumption is clearly expressed with assertions.


There is often a piece of code that can run normally only when a condition is true.

This assumption is generally not explicitly presented in the code. You must read the entire algorithm to see it. Sometimes programmers write such assumptions in comments. Assertions can be used to clearly indicate these assumptions.

Assertion is a conditional expression and should always be true. If it fails, it is not a programmer who has made a mistake. So the failure of assertion should lead to an uncontrolled exception. Assertions cannot be used by other parts of the system. In fact, the final product of the Program often deletes the assertions. Therefore, marking "Something is an asserted" is very important.

Assertions can be used as an aid for communication and debugging. From the perspective of communication, assertions can help the program reader understand the assumptions made by the Code; from the perspective of debugging, assertions can grasp them from the closest to the bug.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.