Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
开发者_运维知识库 Improve this questionI often write functions with conditional branches like this:
function f
if(X) {
do something minor;
}
else if(Y) {
do something minor;
}
else {
do a whole lot of stuff;
}
I could achieve the same results doing:
function f
if(X) {
do something minor;
return;
}
if(Y) {
do something minor;
return;
}
do a whole lot of stuff
I like that the second one doesn't require I indent the majority of my code, but am not sure if this is considered good practice or not. Since there's no common code following the conditional it seems justifiable to do a hard return. But the first style seems to have merits also.
Personally I think using lots of return statements can make code less readable
I often layout my code so that the 'main' body of a function doesn't all have to be indented, in your case:
function f
if (X || Y) {
if (X) do something minor;
if (Y) do something minor;
return; // with comment explaining what we're doing
}
do a whole lot of stuff
First; by now, you should use an editor that takes care of indention for you.
Second; Having several return statements can be confusing. One function one exit point.
Third; If "a whole lot of stuff" could be written as separate functions, do it.
But then again, it's all a matter of taste.
Try using switch/case:
function f
{
switch(Z)
{
case X:
do something...
break;
case Y:
do something...
break;
default:
f2();
}
}
function f2{do other stuff...
}
精彩评论