Can return and else statements be used interchangeably in CFScript?
I开发者_如何转开发 would like to know your opinion on using return
and else
statements interchangeably in CFScript. I generally use the following syntax:
if (something) {
// Do something
}
else {
// Do something else
}
It recently occurred to me I could do this instead:
if (something) {
// Do something
return;
}
// Do something else
Would those two styles yield a different end result? I like not having to wrap code in an else
statement. My thinking is that if the if
statement evaluates true and returns, the code below it will not run. If it does not evaluate true, then the code below it will run regardless of whether it is wrapped in an else
statement or not.
Does that sound right?
Coldfusion like most languages provides many ways of accomplishing the same thing. The job of the programmer is to pick the correct one for the situation. Of course "correct" can have many interpretations but I would say the correct way is clear, concise and scalable.
In this case there are no real performance or "lines of code" differences. Using a return for an entirely different branch of code is not clear to my eyes however, using early return style to bail out of a function due to invalid conditions is (again IMO) more clear. Consider the following cases:
if (not isdefined("url.param1")) {
return;
}
if (not len(url.param1)) {
return;
}
if (not refind("[0-9]+", url.param1)) {
return;
}
doSomethingToValid(url.param1);
versus
if (isdefined("url.param1")) {
if (len(url.param1)) {
if (refind("[0-9]+", url.param1)) {
doSomethingToValid(url.param1);
}
}
}
In the first case I can see all of the validation which will be applied in a list and I can get it all out of the way up front which lets me focus on the real substance of the routine. In the second case I have buried the substantial part of the routine deep in a nested section of ifs and when I need to add another rule to the validation that code structure just gets more complex.
The two ways of writing it will return the same results, but for readability the first way is prefered
精彩评论