Branching statement: better a break or a return inside a for/while cycle?
Obvious开发者_开发百科ly with return only in the case that the method can immediately exit
for (...) {
return;
}
or
for () {
break;
}
Which is better?
The two examples you gave aren't exactly equivalent so it's a little difficult to say which is better style. Here are two approaches that are slightly more similar in what they do:
for (Foo foo: foos) {
// ...
if (ok) { return foo; }
}
return null;
Versus:
Foo result = null;
for (Foo foo: foos) {
// ...
if (ok) {
result = foo;
break;
}
}
return result;
In this case I'd recommend the first because it's much simpler. It is unlikely that there is a significant performance difference. Some people prefer the second because they only want a single return in each function, but I don't think it is always a good idea to stick to that rule. Sometimes multiple return statements makes things much clearer.
I would rather suggest the break approach. It looks like more code but is easier to understand. Also, making changes later is easier. You can go for labeled loops for clarity.
Obviously with
return
only in the case that the method can immediately exit
You've answered your own question. These two have different semantics and aren't really interchangeable, and the return
variant is applicable only to more specific scenarios...
...thus precisely in those specific scenarios you should use the return
variant. The intention is immediately obvious and thus it makes for better readability. If you use a break
when return
suffices, then the reader must spend more time to figure out what happens after the break
. When nothing significant happens, a return
would've quickly conveyed this much more clearly.
精彩评论