简体   繁体   English

我应该使用return / continue语句而不是if-else吗?

[英]Should I use return/continue statement instead of if-else?

In C, C++ and C# when using a condition inside a function or loop statement it's possible to use a continue or return statement as early as possible and get rid of the else branch of an if-else statement. 在C,C ++和C#中,当在函数或循环语句中使用条件时,可以尽早使用continue语句或return语句,并删除if-else语句的else分支。 For example: 例如:

while( loopCondition ) {
    if( innerCondition ) {
        //do some stuff
    } else {
        //do other stuff
    }
}

becomes

 while( loopCondition ) {
    if( innerCondition ) {
        //do some stuff
        continue;
    }
    //do other stuff
}

and

void function() {
    if( condition ) {
        //do some stuff
    } else {
        //do other stuff
    }
}

becomes

void function() {
    if( condition ) {
        //do some stuff
        return;
    }
    //do other stuff
}

The "after" variant may be more readable if the if-else branches are long because this alteration eliminates indenting for the else branch. 如果if-else分支很长,则“after”变体可能更具可读性,因为此更改消除了else分支的缩进。

Is such using of return/continue a good idea? 是这样使用返回/继续一个好主意? Are there any possible maintenance or readability problems? 是否有任何可能的维护或可读性问题?

My personal approach of choosing one is that if the body of the if part is very short (3 or 4 lines maximum), it makes sense to use the return/continue variant. 我个人选择的方法是,如果if部分的主体非常短(最多3或4行),则使用return/continue变体是有意义的。 If the body is long, it's harder to keep track of the control flow so I choose the else version. 如果身体很长,那么跟踪控制流程就更难了,所以我选择了else版本。

As a result, normally, this approach limits the usage of return/continue style to skip some data and avoid further processing rather than process this using one of the following methods (which is better suited by if/else ). 因此,通常,此方法限制return/continue样式的使用以跳过某些数据并避免进一步处理,而不是使用以下方法之一处理此方法if/else更适合)。

The compiler will almost certainly generate the same code. 编译器几乎肯定会生成相同的代码。 Even if it didn't, the difference will be probably irrelevant. 即使它没有,差异可能是无关紧要的。 Hence, the relevant argument is certainly how people would read it. 因此,相关论点肯定是人们如何阅读它。

Therefore the question is how similar "//do some stuff" and "do other stuff" are. 因此,问题是“//做一些东西”和“做其他东西”是多么相似。 If they are conceptually similar, use if/else. 如果它们在概念上相似,请使用if / else。 If they're conceptually different, use continue/return. 如果它们在概念上不同,请使用continue / return。

It depends a little on how long the branches are. 这取决于分支的长度。 The use of return/continue that you describe is good if the initial if check is short, and the body is long. 如果初始if检查很短,并且正文很长,那么使用你描述的return / continue是好的。 If both if and else parts are long, I would extract them to separate functions. 如果ifelse部分都很长,我会将它们提取到单独的函数中。

I recommend reading Code Complete, it discusses things like this a lot. 我建议阅读Code Complete,它会讨论很多这样的事情。

The code would be more readable if termination criteria are handled first. 如果首先处理终止条件,则代码将更易读。 I always prefer, checking for conditions that require a break or return rather than those that would need lengthy code execution. 我总是喜欢,检查需要中断或返回的条件而不是那些需要冗长代码执行的条件。 I prefer: 我更喜欢:

 if (termination condn) 
      return;
 // code 
 // code

to

if (success condn)
{
  // code
  // code
}
else
 return;

This makes reading and understanding the code easier. 这使得阅读和理解代码更容易。

The glib answer is that it all depends. 巧妙的回答是,这一切都取决于。

My general feeling is that if condition is a rare, guard (eg check for null) or error condition then I tend to use return or continue 我的一般感觉是,如果condition是罕见的,保护(例如检查为空)或错误条件,那么我倾向于使用returncontinue

If it's an expected case then I tend to use your first approach. 如果这是一个预期的案例,那么我倾向于使用你的第一种方法。

Notice, however, that I said "tend". 但请注意,我说“倾向”。 The boundary between these to conditions is vague and subject to change depending on the project and who I'm working with. 这些条件之间的界限是模糊的,可能会根据项目和我正在与谁合作而变化。

I usually prefer 我通常更喜欢

while( loopCondition ) {
    if( innerCondition ) {
        DoStuff();
    } else {
        DoOtherStuff(); 
    }
}

continue can be hard to follow if the length of DoStuff passed the 1-2 line threshold (and its fairly easy to miss the intention). 如果DoStuff的长度超过1-2行阈值(并且很容易错过意图),则很难继续。 This seems like a good opportunity to refactor the logic into some smaller methods. 这似乎是将逻辑重构为一些较小方法的好机会。

Do not sacrifice readability for premature optimization. 不要为了过早优化而牺牲可读性。

For example: 例如:

void function() {
    if( condition ) {
        //do some stuff
    } else {
        //do other stuff
    }
}

is in most cases binary equivalent to 在大多数情况下二进制等价于

void function() {
    if( condition ) {
        //do some stuff
        return;
    }
    //do other stuff
}

(ie the resulting code is probably the same). (即结果代码可能相同)。 But the readability of the former is much better, because you can clearly see that the code will to either X or Y. 但是前者的可读性要好得多,因为你可以清楚地看到代码将是X或Y.

1) Input or object state validation . 1) 输入或对象状态验证 Following code: 以下代码:

void function() {
    if( condition ) {
        //do some stuff
        return;
    }
    //do other stuff
}

is good when the condition is some requirement for function to work. 当条件是功能工作的一些要求时,这是好的。 It's a stage of input validation or object state validation. 这是输入验证或对象状态验证的一个阶段。 It then feels right to use return immediately to emphasis, that function did not run at all. 然后,立即使用返回来强调它是正确的,该功能根本没有运行。

2) Multistage processing . 2) 多级处理 While/continue is good when the loop pops elements from some collection and processes them in multistage manner: 当循环从某个集合中弹出元素并以多级方式处理它们时,/ continue很好:

while(foo = bar.getNext()) {
   if(foo.empty())
       continue;
   if(foo.alreadyProcessed())
       continue;
   // Can we take a shortcut?
   if(foo.tryProcessThingsYourself())
       continue;
   int baz = foo.getBaz();
   if(baz < 0) {
       int qux = foo.getQux();
       if(qux < 0) {
         // Error - go to next element
         continue;
       }
   }
   // Finally -- do the actual processing
   baz = baz * 2;
   foo.setBaz(baz);
}

The example shows how natural it is to use continue in scenario when series of multistage processing is done, when each processing can be interrupted by various conditions in various places. 该示例显示了在完成一系列多级处理时,在每个处理可能被各个地方的各种条件中断时,使用“ 继续 ”的自然程度。

Notice: plinth posted real-life example, which follows what 2) says. 注意: plinth发布了真实的例子,它遵循2)所说的。

3) General rule . 3) 一般规则 I use continue and return when it corresponds with fact that something has been interrupted. 我使用continue返回,因为它与某些事物被中断的事实相对应。 I use else , when the else is part of actual processing. else是实际处理的一部分时,我使用else

One possible maintenance issue is that if a function has multiple returns, then it is harder to stick a breakpoint or tracing at the return when debugging. 一个可能的维护问题是,如果一个函数有多个返回,那么在调试时很难在返回时粘贴断点或跟踪。 This is only rarely an issue, but when you do miss a return point it's a pain. 这很少是一个问题,但当你错过一个回归点时,这是一个痛苦。 I don't think it matters so much for continue in loops, since the loop condition and the top of the loop are both still unique. 我认为继续循环并不重要,因为循环条件和循环顶部都是唯一的。

Aside from that: what everyone else says. 除此之外:其他人都在说什么。 Do what's most readable, which depends on the relative length, importance, and likelihood of "some stuff" and "other stuff". 做什么是最可读的,这取决于“某些东西”和“其他东西”的相对长度,重要性和可能性。 The shorter, more trivial, and more unlikely a case is, the less disturbing it is for it to have special-case control flow. 更短,更琐碎,更不可能的情况是,它具有特殊情况控制流程的不那么令人不安。

as other people said, only use return/continue if things are short. 正如其他人所说,如果事情很短,只能使用返回/继续。

Personally i only use continue if it is possible to write on one line like: 我个人只使用continue,如果可以在一行写,如:

while( loopCondition ) {
    if( innerCondition ) continue;

    //do other stuff
}

If it's not possible to write it like this without code getting ugly, then if / else. 如果在没有代码变得丑陋的情况下不可能这样写,那么if / else。

For grins, I did a search across my company's codebase for "continue;" 为了笑容,我在我公司的代码库中搜索了“继续”; just to get an idea of where it's being used. 只是为了了解它的使用位置。 We use if 695 times across 59 projects in one solution, roughly 1500 source files. 我们在一个解决方案中使用59个项目的695次,大约1500个源文件。

The main ways I see them being used are as a quick filter: 我看到它们被使用的主要方式是作为快速过滤器:

foreach (Frobozz bar in foo) {
    if (QuickFilterExclude(bar))
        continue;
    // extensive processing
}

A recovery from an expected exception: 从预期的异常中恢复:

foreach (Frobozz bar in foo) {
    Baz result = new Baz(kDefaultConfiguration);
    try {
        Baz remoteResult = boo.GetConfiguration();
    }
    catch (RemoteConnectionException) {
        continue;
    }
    result.Merge(remoteResult);
    ReportResult(result);
}

And finally in state machinery. 最后是国家机器。

I generally use the if-return method when jumping out of a method or loop because there is nothing to be done. 跳出方法或循环时,我通常使用if-return方法,因为没有什么可做的。

If the body is longer because substantial work is being done, I suggest using if-else and maybe using #region to give blocks a sensible name and have them easily collapsable for people to study the control flow. 如果身体因为大量的工作而更长,我建议使用if-else并且可能使用#region为块提供合理的名称并让它们容易折叠以供人们研究控制流程。 That or make separate methods :) 那个或制作单独的方法:)

I had the following in my code: 我的代码中有以下内容:

    while(){
      boolean intersect = doesIntersect(interval_1,interval_2);
      if(!intersect){
         array.add(interval_2);
         if(// another condition){
            // Do some thing here
         }
         continue;
      }
      // other stuff to do if intersect
    }

Was confusing whether I should use continue there or use else but I decided that the inner if condition might make the else not well readable, so I used continue. 令人困惑的是我是否应该继续使用或使用其他但我决定内部if条件可能使其他人不能很好阅读,所以我用继续。

I think readability is what matters! 我认为可读性才是最重要的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在方法返回的If-Else语句中,是否可以明确声明是否可以隐式遵循? - In an If-Else Statement for a method return, should an Else be explicitly stated if it can instead be implicitly followed? 如何使用if-else语句中陈述的值? - How to use values stated in the if-else statement? Try-Catch与If-Else | 我应该在这种情况下争取使用If-Else还是只使用Try-Catch? - Try-Catch vs If-Else | Should I fight to use If-Else in this or just go with the Try-Catch? 使用“ null”开关语句来确定文本框范围是否为空,而不是使用if-else语句 - Use a “null” switch statement to determine if a range of TextBoxes are null, instead of using if-else statements 仅使用“ if-else”语句的“ else”部分是否可以接受? - Is it acceptable to only use the 'else' portion of an 'if-else' statement? 复选框的If-Else语句 - If-Else statement for a checkbox 返回调试信息的好方法,而不是使用大量的if-else - Better way to return debug information instead of using lots of if-else 在分配它的if-else语句中使用未分配的局部变量 - Use of unassigned local variable in an if-else statement that assigns it 在if-else语句范围之外定义var以供以后使用 - Define var outside the if-else statement scope for later use 我如何使用switch语句而不是太多其他语句 - How Can I use switch statement instead of too many else if
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM