When to use 'if…else if' and when to use
- You should probably use the first. It's more accepted, and more logical. (You don't care about anything afterwards if this condition is true... indicate that in your code.)
- It's generally more accepted, and more compact and readable, to use the first way (else if). Python even has a specific keyword for it (elif).
I personally would use
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
if (value >= bigNumber)
return bigNumberDescription;
if (value >= smallNumber)
return smallNumberDescription;
return string.Empty;
}
It really all depends on what your function is doing. If its simple like this then keep it simple. If you might need to do something with the result before you return it then I'd use Egrunin's solution
protected string GetNumberDescription(int value)
{
string ret = "";
if (value >= veryBigNumber)
ret = veryBigNumberDescription;
else if (value >= bigNumber)
ret = bigNumberDescription;
else if (value >= smallNumber)
ret = smallNumberDescription;
return ret;
}
The question is already answered, but I added this because:
- There are advantages to having a single exit from a function.
- The same variable is being tested repeatedly, so the if/elseif is most appropriate.
Edited to add:
I'm usually a big fan of exiting a function early in cases like this:
if (conditionOne)
{
if (conditionTwo)
{
if (conditionThree)
{
interesting_stuff();
}
}
else
boring();
}
return;
I'm much happier seeing this:
if (!conditionOne)
return;
if (!conditionTwo)
{
boring();
return;
}
if (!conditionThree)
return;
interesting_stuff();
return;
But when there are exits at many different nesting levels, it's too easy to miss one as you're reading over the code.
Also, as mentioned in the comments: a single exit means only one place to put a breakpoint.