Should I save a result from a switch statement before returning it? Or should I return the value in the switch when I get it? Is there one way over another that is better style?
With a temporary variable:
public double xMax {
get {
double val = 0.00f;
switch(x_option) {
case 0:
val = priMax;
break;
case 1:
val = rfMax;
break;
case 2:
val = pwMax;
break;
}
return val;
}
}
With return statement:
public double xMax {
get {
double val = 0.00f;
switch(x_option) {
case 0:
return priMax;
case 1:
return rfMax;
case 2:
return pwMax;
}
}
}
Is there a performance difference and/or cleanup?
Personally I prefer the second form. It makes it immediately clear that as soon as you’ve got to the return statement, you’re done. With the extra variable version, you have to look through the rest of the code to see if anything else will happen.
The dogma around a single point of return made sense in C, where you’d want to make sure you did all your manual clean-up etc – but in a world where you have to consider the possibility of exceptions anyway, and the garbage collector handles most of the cleanup, with
try/finallyhandling the rest, I find there are a lot of cases where insisting on a single exit point makes the code significantly harder to read – particularly around cases where you can determine the result right at the start of the method (e.g. “if the input string is empty, the result is always going to be 0 – so just return it there).EDIT: Just to be clear, in your situation I don’t think it makes much difference. But this is the kind of code where single point of return gets messy:
With a single point of return, this would become:
I would definitely rather read the first form than the second: