如果-否则或提前返回 [英] if-else or early return
问题描述
有时候我喜欢使用早期的return语句来防止嵌套if语句,我发现这样会使代码的可读性降低.
Sometimes I like to use early return statements to prevent nesting if statement, which I find makes for less readable code.
我想知道是否有任何客观或压倒性的普遍共识,所以以下两种模式哪个是更好的实践?我不认为这是一个主观的问题,因为我真正要问的是几乎是客观的偏好.
I am wondering if there is any objective or overwhelming general consensus as two which of the following patterns is better practice? I don't think this is a subjective question, since what I am really asking is there a near objective preference.
void func() {
if (a) {
do b
}
else {
do c
}
}
或
void func() {
if (a) {
do b
return;
}
do c
}
推荐答案
第一个更好.简而言之,它可以帮助另一个开发人员理解c的编译,因为条件是错误的.它还可以防止其他人对您的代码进行破坏性的更改.也就是说,它们都是正确的,并且都可以正常工作
The first is better. Simply put,it helps another developer to understand that c compiles because the condition is false. It also prevents other people from making damaging changes to your code. That said,they are both correct and would both work just fine
这篇关于如果-否则或提前返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!