I'd been told, that using "if" statements is preferred , because of harder debugging of the code, when "else if" is used? Is there a grain of truth in this statement?
I've never had issues debugging 'else if' statements. I think using 'else if' statements are clean and it communicates to a programmer reading the code that the group of 'else if' statements are mutually exclusive.
I think this is not true. An if, else if statement is fairly simple and easy to debug. I guess it may depend on the person who is debugging, but in my experience there is not a single difference, and I haven't heard anyone screaming "darn you else if!" while debugging his code.
if(...)
{
}
else if(...)
{
}
is completely equivalent to:
if(...)
{
}
else
if(...)
{
}
in the same way that:
if(...)
foo();
else
bar();
is totally equivalent to:
if(...) foo();
else bar();
It's 100% style, and whether one is more or less readable than another is a total judgment call based on your programming culture, language and how complex the statement is.
The difference between if
and else if
is the same as the one between coordinating and exclusive conjunctions.
if "else if" is a non-preferred construct, then why does practically every modern language provide for it? I think your fine with continued use of else ifs... besides - by the time it hits assembly, its all a jump/goto anyway ;)
Maybe your boss just means to reccomend early returns.
I don't often need if / else
. But that is not because else
is wrong, but because I like early returns, and if you use early returns, you don't need else that much.
So rather than:
boolean validate(DomainObject o) {
boolean valid = false;
if (o.property == x) {
valid = true;
} else if (o.property2 == y) {
valid = true;
} ...
return valid;
}
I prefer to type:
boolean validate(DomainObject o) {
if (o.property == x)
return true;
if (o.property2 == y)
return true;
return false;
}
I have to disagree as well. There's nothing inherently more difficult about an "else if"; whether it's the right programming approach depends on each application. In some cases, a "switch" or "case" statement is better but, again, that depends on the application.
Making a hard rule like that is too limiting, in my opinion.
Both forms take the same debugging effort. I would dare to say that "else if" statements actually make debugging easier...
In addition, "else if" statements increase performance, because your program doesn't have to check conditions that are actually mutually exclusive!
The statement "else if is harder to debug" is ridiculous. I suggest that you not ask that individual for help in the future.
Use the solution that is semantically correct. If the solution is:
if a is true do a.action
if a is not true and b is true, then do b.action
otherwise do c.action
then else if
is appropriate. For example:
if (a == true)
{
// do a.action
}
else if (b == true)
{
// do b.action
}
else
{
// do c.action
}
If the solution is:
if a is true do a.action
if b is true do b.action
if c is true do c.action
then else if
is not appropriate. For example:
if (a == true)
{
// do a.action
}
if (b == true) // note that we don't care if a was true
{
// do b.action
}
if (c == true) // care about neither a nor b
{
// do c.action
}
In normal use, there is nothing wrong with else if
at all. In fact, I'd consider it a vital coding technique.
The only time else if
is a problem is when you chain loads of them together - I've had to debug legacy code which had thousands of lines, consisting of page after page of if, elseif, elseif, elseif...... ad infinitum. Now that is bad code. Don't do that.
That's the sort of thing which maybe gave you a bad experience of else if, but that's just bad coding; you could do just as bad or worse without else if.
Why don't you try search n replacing all else ifs with ifs in your code? it will compile but it will only execute as desired if you are lucky ...
It just is not the same and there is a reason why there is If and why there is Else IF.
Ex:
if(3<5) {
print('blah');
} else if(4<5) {
print('blub');
}
// blah
if(3<5) {
print('blah');
}
if(4<5) {
print('blub');
}
// blahblub
and i personally prefer oranges! apples are so olschool ... i think bananas are fine too (but this switches from time to time!)
there is also the switch statement.
those control structures all do something different and are not redundant, thats why they are all there. and you cannot say it doesnt matter which to use, it also isnt a matter of style or better readable code or something.
i would even say for every use case there is one optimal control structure to use!
consider theese examples:
if(money > 2000) {
switch ($what-car-does-my-wife-want) {
case "ferrari":
echo "buying a ferrari";
break;
case "chevvy":
echo "buying a chevvy";
break;
case "bmw":
echo "buying a bmw";
break;
}
} else {
echo "i better not buy a new car";
}
if(money > 5000) {
echo "wow i can buy a lot of other things too!";
} else if(3000) {
echo "wow that is a lot of money but i wish i had 5000!";
}
the only thing you can do and which is a question of style is replacing
if(money > 5000) {
echo "wow i can buy a lot of other things too!";
} else if(money > 3000) {
echo "wow that is a lot of money but i wish i had 5000!";
}
by
if(money > 5000) {
echo "wow i can buy a lot of other things too!";
} else {
if(money > 3000) {
echo "wow that is a lot of money but i wish i had 5000!";
}
}
but i think that isnt what you asked?
You are comparing
if (a=b) do this;
if (a=c) do this;
if (a=d) do this;
To:
if (a=b) do this;
else if (a=c) do this;
else if (a=d) do this;
1) the first example harder to debug because you don't have a natural workflow for your code like the second example provides.
2) as Jason pointed out, the first example performs differently than the second inasmuch as all three if statements will be tested no matter what, whereas the second example will stop testing when it becomes true.
tl;dr: Your boss is wrong, despite the fact he also has an internet access.
I like the old saying “debugging is twice as hard as writing code so if you write the code as clever as you can you are by definition not clever enough to debug it”. So I try to make my code easy to read & debug (sometimes this isn’t possible). That being said, I don’t think an else if is very clever, so I would continue using it.
It's a heck of a lot better than:
if (a=1) then {
DoThis;
EXIT; // Not sure if this works in your language, but you know what I mean...
}
if (a=2) then {
DoThis;
EXIT;
}
if (a=3) then {
DoThis;
EXIT;
}
Whatever way you write it, you should have in your mind that the language syntax can be used to improve code readability and to remark to your coworkers what was the idea behind those lines of code.
So... be wise to choose whichever way. An example of misuse is to imbibe many if
blocks within other code blocks. That can make the code unreadable and unmaintainable.
Perhaps your boss says that because he can't.
The form of an 'if statement' is:
if (condidtion1)
statement1;
else
statement2;
One of the valid forms of a statement is an 'if statement'. Let's make 'statement2' above into the 'if statement' if (condition2) statement3;
if (condition1)
statement1;
else if (condition2)
statement3;
The white-space and positioning is just for your benefit (readability). The compiler knows nothing about 'else if' per se.
This demonstrates that 'if' and 'else if' are not the same thing though. 'else if' is a compound statement.
Another valid form for a statement is a block of statements surrounded in brackets { }. This is why you often (usually) see brackets in an 'if statement'. Whether or not to use them around a single statement is just a matter of style.
The reason to use 'else if' is that you avoid having to process the 'condition' expressions that you know will evaluate to false. You know this because of other conditions you have already checked.
Perhaps your boss is saying that you may make a mistake in these assumptions and that 'else if' statements may hide subtle bugs. I suppose that is certainly possible. It does not seem worth the overhead to me though.
What does he have to say about the 'switch statement'?
It depends on what you're trying to accomplish. Both are acceptable forms of coding, it just depends on what you're doing. For instance, if you want to ensure that every comparison is checked and the possibility of all code being run, you should use the singular if
construction:
if(condition1IsTrue) {
methodThatMustRun1();
}
if(condition2IsTrue) {
methodThatMustRun2();
}
... etc
In this example, all conditions are checked with the possibility of every block of code being run.
If you are only looking to run a single block of code from multiple options, then you should use the if else
construction, preferably in the order of most common to occur to least common:
if(condition1IsTrue) {
mostCommonMethodToRun();
} else if (separateConditionToCheckInCaseFirstFails) {
nextMostCommonScenarioMethodToRun();
} else if (...) {
... etc
}
In this second example, at most all conditions are checked, but potentially only one is checked. However, exactly one block of code is executed (assuming you have a default action in case no conditions evaluate to true).
Your boss isn't necessarily an idiot like everyone is saying, but it's possible that you misunderstood his intention. When you think about it, all conditional code is essentially separate blocks (first example) comprised of some multiple-option code (second example).
However, your boss COULD be an idiot if he says, dogmatically, that you must not ever program in if else
constructs.
I'm a head programmer and sometimes my subordinate misunderstand me. When I talked about specific case, many times they took it as a "rule" and try to enforce it everywhere in the code base. I'm not sure if this is your case or not, or maybe your boss was once my subordinate?
About the question, else if
is fine for me but when there are not too many of them because else if
force you to read all the expression above them to realize when the code inside will get executed.
answer given by JDV seems to be the correct one. I came here to search for an answer of the very simlar type. However the answer selected by the question owner is not the proper/correct one. The proper/correct answer is about early returns and clear styles and it is about the fact that nesting too much if-then-else statement is in general not a good style of programming. And henceforth debugging a poorly written code is always more difficult.
CONCLUSION : the conditional code should be as clear/simple as possible so that either at the programming or at the debugging phase a human being can manage variables involved easily.