1) I know how if…else if
statements work, but in the next example both methods are identical as far as the resulting value is concerned. So does it matter which of the two methods I use or should I always go for one that is semantically closest to what the code is trying to do ( here I’m guessing that semantically the two methods are quite different )? So which method would you use and why?
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
else if (value >= bigNumber)
return bigNumberDescription;
else if (value >= smallNumber)
return smallNumberDescription;
else
return "";
}
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
if (value >= bigNumber)
return bigNumberDescription;
if (value >= smallNumber)
return smallNumberDescription;
else
return "";
}
2) I noticed losts of code uses the following format when writting if ... else if
statements:
if ...
else if ...
else ...
But isn't ( at least conceptually ) more correct way:
if ...
else
if ...
else ...
The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.
Notice that the difference between IF statement and IF-ELSE statement is that there's an additional ELSE attached to it. The IF statement is executed if the statement inside the test condition evaluates to true; otherwise the statements inside the ELSE block is executed.
The main reason to use else if is to avoid excessive indentation. Of course both of the pieces of code above are equivalent (which means it's impossible for the latter to be mandatory other than in style guides).
The elseif and else blocks are optional. The statements execute only if previous expressions in the if... end block are false. An if block can include multiple elseif blocks.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With