Reconstruction Method 34: decompose conditional (decomposition condition expression)

Source: Internet
Author: User

 

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

Motivation:ProgramComplex conditional logic is one of the most frequent locations that lead to increased complexity. You must writeCodeTo check different condition branches and perform different tasks based on different branches, and 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.

Practice: 1. Extract the if section to form an independent function.

2Extract the then and else sections to form an independent function.

If nested condition logic is found, first check whether replace nested conditional with guard clags can be used (replace nested condition expressions with guard statements ). If not, start to break down each of the conditions.

 

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.