Refactoring Method 38: replace nested conditional with guard clses (replace nested condition expressions with guard statements)

Source: Internet
Author: User

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.

Motivation: 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 clausesThe essence of replacing nested condition expressions with Wei statements is to give 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 rooted in someProgramEmployee's mind. Today'sProgramming LanguageEvery function has only one entry. As for the Single Exit rule, it is not so useful. PersistenceCodeClarity 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.

Practice: 1. For each check, put a guard statement. The guard statement does not return from the function, or throws an exception.

2. Compile and test each time you replace the condition check with the Wei statement. If all Wei statements cause the same results, use the merge lidate conditional expression (merge conditional expression ).

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.