When to use If-else if-else over switch statements and vice versa

Switch Statement

Switch Statement Problem Overview


Why you would want to use a switch block over a series of if statements?

switch statements seem to do the same thing but take longer to type.

Switch Statement Solutions


Solution 1 - Switch Statement

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
    doThis();
} else if (value == 2) {
    doThat();
} else {
    doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

Solution 2 - Switch Statement

If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.

Otherwise, stick with multiple if-else statements.

Solution 3 - Switch Statement

concerning Readability:

I typically prefer if/else constructs over switch statements, especially in languages that allows fall-through cases. What I've found, often, is as the projects age, and multiple developers gets involved, you'll start having trouble with the construction of a switch statement.

If they (the statements) become anything more than simple, many programmers become lazy and instead of reading the entire statement to understand it, they'll simply pop in a case to cover whatever case they're adding into the statement.

I've seen many cases where code repeats in a switch statement because a person's test was already covered, a simple fall-though case would have sufficed, but laziness forced them to add the redundant code at the end instead of trying to understand the switch. I've also seen some nightmarish switch statements with many cases that were poorly constructed, and simply trying to follow all the logic, with many fall-through cases dispersed throughout, and many cases which weren't, becomes difficult ... which kind of leads to the first/redundancy problem I talked about.

Theoretically, the same problem could exist with if/else constructs, but in practice this just doesn't seem to happen as often. Maybe (just a guess) programmers are forced to read a bit more carefully because you need to understand the, often, more complex conditions being tested within the if/else construct? If you're writing something simple that you know others are likely to never touch, and you can construct it well, then I guess it's a toss-up. In that case, whatever is more readable and feels best to you is probably the right answer because you're likely to be sustaining that code.

concerning Speed:

Switch statements often perform faster than if-else constructs (but not always). Since the possible values of a switch statement are laid out beforehand, compilers are able to optimize performance by constructing jump tables. Each condition doesn't have to be tested as in an if/else construct (well, until you find the right one, anyway).

However this isn't always the case, though. If you have a simple switch, say, with possible values of 1 to 10, this will be the case. The more values you add requires the jump tables to be larger and the switch becomes less efficient (not than an if/else, but less efficient than the comparatively simple switch statement). Also, if the values are highly variant ( i.e. instead of 1 to 10, you have 10 possible values of, say, 1, 1000, 10000, 100000, and so on to 100000000000), the switch is less efficient than in the simpler case.

Hope this helps.

Solution 4 - Switch Statement

Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch.

Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.

Solution 5 - Switch Statement

The tendency to avoid stuff because it takes longer to type is a bad thing, try to root it out. That said, overly verbose things are also difficult to read, so small and simple is important, but it's readability not writability that's important. Concise one-liners can often be more difficult to read than a simple well laid out 3 or 4 lines.

Use whichever construct best descibes the logic of the operation.

Solution 6 - Switch Statement

I personally prefer to see switch statements over too many nested if-elses because they can be much easier to read. Switches are also better in readability terms for showing a state.

See also the comment in this post regarding pacman ifs.

Solution 7 - Switch Statement

This depends very much on the specific case. Preferably, I think one should use the switch over the if-else if there are many nested if-elses.

The question is how much is many?

Yesterday I was asking myself the same question:

public enum ProgramType {
	NEW, OLD
}

if (progType == OLD) {
	// ...
} else if (progType == NEW) {
	// ...
}

if (progType == OLD) {
	// ...
} else {
	// ...
}

switch (progType) {
case OLD:
	// ...
	break;
case NEW:
	// ...
	break;
default:
	break;
}

In this case, the 1st if has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.

I ended up choosing the switch because it just reads better.

Solution 8 - Switch Statement

Let's say you have decided to use switch as you are only working on a single variable which can have different values. If this would result in a small switch statement (2-3 cases), I'd say that is fine. If it seems you will end up with more I would recommend using polymorphism instead. An AbstractFactory pattern could be used here to create an object that would perform whatever action you were trying to do in the switches. The ugly switch statement will be abstracted away and you end up with cleaner code.

Solution 9 - Switch Statement

I have often thought that using elseif and dropping through case instances (where the language permits) are code odours, if not smells.

For myself, I have normally found that nested (if/then/else)s usually reflect things better than elseifs, and that for mutually exclusive cases (often where one combination of attributes takes precedence over another), case or something similar is clearer to read two years later.

I think the select statement used by Rexx is a particularly good example of how to do "Case" well (no drop-throughs) (silly example):

Select
	When (Vehicle ¬= "Car") Then
		Name = "Red Bus"
	When (Colour == "Red") Then
		Name = "Ferrari"
	Otherwise
		Name = "Plain old other car"
	End

Oh, and if the optimisation isn't up to it, get a new compiler or language...

Solution 10 - Switch Statement

Switch statements are far easier to read and maintain, hands down. And are usually faster and less error prone.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionK2JView Question on Stackoverflow
Solution 1 - Switch StatementtddmonkeyView Answer on Stackoverflow
Solution 2 - Switch StatementGarry ShutlerView Answer on Stackoverflow
Solution 3 - Switch StatementAllen RatcliffView Answer on Stackoverflow
Solution 4 - Switch StatementSergioView Answer on Stackoverflow
Solution 5 - Switch StatementAnthonyWJonesView Answer on Stackoverflow
Solution 6 - Switch StatementSmacLView Answer on Stackoverflow
Solution 7 - Switch Statementbruno condeView Answer on Stackoverflow
Solution 8 - Switch StatementwillcodejavaforfoodView Answer on Stackoverflow
Solution 9 - Switch StatementBrent.LongboroughView Answer on Stackoverflow
Solution 10 - Switch StatementEldelshellView Answer on Stackoverflow