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 ).