Apart from code readability, why is it bad to use lots of if statements?
-
Most programs have lots of if-statements. I have never heard that this is bad. Are you perhaps referring to *deeply-nested* if-statements? – Marcelo Cantos Dec 02 '10 at 11:20
-
1I don't know, is it? In what context? – H H Dec 02 '10 at 11:21
-
One problem is that you are introducing a lot of code paths. This makes it difficult to test the code. It can be hard to trigger each path separately. Better to find usable design patterns such as the mentioned strategy. That would allow you to much easier test each individual code path. – Daniel Lidström Dec 02 '10 at 12:05
9 Answers
Every if/else you write increases the number of code paths you have to test.

- 40,496
- 12
- 101
- 170
If you have a lot of if statements one after the other, then a switch case statement is more useful. At least it has a fixed response time for each possible inupt as it does not need to fall through all the if statements.
A lot of if (and else) statement usually indicates
a) Violation of Single responsibility Principle
b) Need to refactor out into Strategy Design Pattern

- 24,777
- 4
- 73
- 129
-
5A `switch` statement doesn't necessarily have a fixed response time (at least not in C#). Having said that, worrying about these kind of ultra-micro-optimisations is a waste of time for pretty much everybody. – LukeH Dec 02 '10 at 11:37
-
3@LukeH : I actually spent most of yesterday tracking down branch penalties in my app and either eliminating them or replacing them with branchless algorithms, in order to knock a 250ms hitch down to 50ms. – Crashworks Dec 02 '10 at 11:50
-
@Crashworks: That's why I said *"pretty much everybody"* rather than just a blanket *"everybody"*. I suspect that you're one of the exceptions that proves the rule. – LukeH Dec 02 '10 at 11:58
-
1@LukeH, @Crashworks I know I'd also much rather trace such a penalty in easy to read code than in code someone had made unreadable about what is "probably more efficient". So, even when considering the case where such optimisations are important, it still weighs on starting with the more readable code and ignoring efficiency concerns you can't be sure of. – Jon Hanna Dec 02 '10 at 12:09
Well, the question I have to ask back is, "as opposed to what"?
If you mean as opposed to a switch statement, then as well as readability it can sometimes be more efficient. As a rule (certainly in C#, likely in the others) below a certain number of branches it will just be turned into a series of if statements when compiled but beyond that number it will be turned into a hash-based lookup and jump that is likely to be faster on the average case.
Alternatively, if you have good knowledge of the relative frequency of different cases, you can be more efficient with a set of if statements. E.g. if 95% of cases match the first branch, 4% match the second and 1% match all the rest, this can give better performance for the 95% of cases by doing a single comparison and perhaps not even branching in that case.
So. Maybe there's an efficiency gain in this case.
Still, readability counts for a hell of a lot. As an extreme example, there's a Turing-complete language that was designed just for the sake of seeing how small a compiler for a Turing-complete language could be. It's designer named the language "brainf**k". This in itself is a great comment on the importance of readable code in real programming.
Now, a bigger issue with a large number of if statements, is that it often indicates that you are modelling something through those if statements that could be modelled better with a class hierarchy. In a way this is just another take on readability (assuming the program works either way). However, it's about the readability - and understandability - of the program as a whole. It will massively impact upon the mental model you have of the program, extensibility and affect not just how well you can maintain it, but you will conceive of as possible with it. It can easily be the difference between a program that becomes a legacy time-sink until someone works out how to get rid of it, and one that grows to continue to give return on investment.

- 110,372
- 10
- 146
- 251
Sometimes because of processor architecture, it's more efficient to find a way to avoid branching at all; this could be considered a disadvantage of if
statements.

- 36,141
- 15
- 83
- 142
Chusdad is right. Switch structure is better than multiple if-else. The next approach is to use enum as a switch key. In this case you get warning if you forgot to mention one of enum elements in your switch.
But if you are using enum and switch, go forward for better design: remove switch at all!
Declare abstract business method in your enum. Implement it for each enum element. The call enumElement.theMethod() instead of implementing switch.
Here is an example.
enum Foo {
ONE {
public void foo() {
// do something
}
},
TWO {
public void foo() {
// do something
}
},
;
public abstract void foo();
}
Here is the code that uses this:
Foo.valueOf(System.getProperty("foo")).foo();
Compare this line with the following:
String foo = System.getProperty("foo");
if("ONE".equals(foo)) {
//.....
} else if("ONE".equals(foo)) {
//.....
} else {
//.....
}
I think that no comments are required.

- 130,161
- 59
- 324
- 434

- 114,158
- 16
- 130
- 208
if(A)
{
}else
if(B)
{
}else
if(C)
{
}else
if(D)
{
}else
{ }
All if
s will still have to get "calculated" making it something like "O(n)". It should be avoided when possible and use switch(Lalala)
-
1if you are using `else` then remaining `if` s after a matching condition are not evaluated. It is worse case only when no `if` matches and the last `else` is executed. – TheVillageIdiot Dec 02 '10 at 11:24
-
@TheVillage, yes this is what I am referring to. The default: case in switch. eg. if C would be the matching condition, then A and B would still have to be evaluated. but with switch we could "jump" straight to C. – Dec 02 '10 at 11:25
-
-
never mind. But you cannot use switch in all situations. To use switch you need `constant` values for `case`. – TheVillageIdiot Dec 03 '10 at 06:33
Another possibility - it depends what the if statements are doing. In some cases, they can be making decisions that are better done by a properly designed class hierarchy.
Can you post some examples of if statements you have been told are bad?

- 41,321
- 20
- 104
- 134
If statement can produce a stall in the pipeline. You can read about pipeline Hazards here. So, for very performance critical applications it is not a good idea to have many if statements in a big loop. Check also this article about branch prediction in modern processors, and benchmarks of various if conditions.
Also, I see a lot of people talk about case statement. Check this SO thread.
And for the end, wiki article about pipeline that probably every programmer should have read.
Hope it helps.
If you find yourself writing if
statements for the same condition over and over, then it will be more maintainable to make that part of the type hierarchy.
The reason is that if the logic for this condition changes, you will need to hunt down every if
statement that uses it and modify it.
If that logic is encapsulated in a class hierarchy, you should only need to change it once.

- 8,709
- 6
- 42
- 49