views:

932

answers:

21
+7  Q: 

"if' VS "else if"

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?

+40  A: 

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.

ChrisNel52
+1 couldnt agree more. IMO, having separate IF statements instead of elseif for conditions that are mutually exclusive just makes it so much harder when debugging.
InSane
+1 So true. If someone new inherits the code, makes it easy for them to understand what it was meant to do.
Nikki9696
If (you say that) {i don't agree} else if (true) {i agree}. or was it if(you say that) { i don't agree } if(true) {i agree} ? you should rather ask wether to prefer if or switch but then i'd answer i would switch from switch to elseif which can do comparisions. it just isnt the same it never will be and there is areason why there is both and its not a matter of style or so. i would even say for every use case there is one optimal control structure.
Joe Hopfgartner
But there's no such thing as an "else if" statement. There's an "else" part of one "if" statement that happens to be followed immediately by another "if" statement (and one of the best known shift/reduce conflicts, resolved by a "prefer to shift" rule IIRC). Some languages have an "elseif" or an "elsif", but if you see "else if" that's probably not a grammar clause in itself.
Steve314
+1  A: 

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.

Seth Illgard
+4  A: 

If/If else statements don't make bad code, I do

Nick DeVore
+1 fair enough ;)
Rook
+8  A: 
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.

KeithS
I sort of think that "else if" is more readable once you start adding more and more "else if" blocks as it keeps the code left justified as opposed to gradually creeping to the right as you indent more and more.
Peter M
+8  A: 

The difference between if and else if is the same as the one between coordinating and exclusive conjunctions.

wok
I mean there is no way one could recommend one over the other.
wok
A: 

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 ;)

chrismh
+4  A: 

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; 
}
jdv
I quite like early returns as well, but I do know quite a lot of programmers who are very fastidious about only having one exit point from a function.
Spudley
jdv
+1 for early returns. if..else and more often leads to multiple levels of nested conditions, signs of bad style, which in turn may lead to the 'harder to debug' symptom because it's harder to memorize the complete path from the beginning of the method to the point down at level 4, until the kickback happens.
mhaller
@mhaller: That is a matter of preference. With early exits it becomes harder to remember the condition under which the code farther down a method is acutally executed. And you are not alerted to these conditions existing as the code is not indented... Now methods should of course not be too long anyway, so the conditions up above shouldn't scroll from view, but we do not live in a perfect world and it all comes down to balancing the pro's and con's of various styles and not declaring one style bad just because it doesn't suite the way your mind works.
Marjan Venema
I rather use the second option too.
Sergio Rodriguez
A: 

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.

Chuck
A: 

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!

Rui Curado
+1  A: 

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
}
dwb
@dwb: I have cleaned up your answer for you. In the future please don't post HTMl like that; use the built-in markdown functions instead.
Josh
Given that the person advising him is his employer/manager, I suspect he didn't have to ask for it in the first place...
David Thomas
+2  A: 

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.

Spudley
A: 

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?

Joe Hopfgartner
A: 

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.

Moses
Beyond the efficiency problem posed by redundant compares in the former example, understanding the code requires determining whether 'a' can ever be set to a future value, and knowing whether that's a good or a bad thing. In an if-elseif construct, exactly one case will execute, even if the code for an earlier case sets up a condition that /would have/ triggered a later one.
supercat
@moses, this is not correct. they do not function the same. your first example will make exactly 3 comparisons while your last example will make *at most* three comparisons. In javascript especially, this is a very important distinction.
Jason
Think of if actually b == d XD
PeterWong
+2  A: 

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.

Rossini
A: 

just say your boss that he is right and everything is cool. lol

vertazzar
That really isn't good advice, should be a comment not an answer. I wont negate you but im just letting you know.
JonH
A: 

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;
}
Chris Thornton
A: 

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.

JPCF
A: 

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'?

Justin
A: 

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.

Jason
A: 

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.

tia
A: 

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.