views:

1111

answers:

10

Hi I was just wondering if anyone has any tips over why you would want to use a switch block over a series if statements.

Switch Statements seem to do the same thing but take longer to type.

A: 

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.

Garry Shutler
A: 

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

Use which ever construct best descibes the logic of the operation.

AnthonyWJones
+1  A: 

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.

Shane MacLaughlin
+2  A: 

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)

MrWiggles
Another way of making it more readable (and looks good in a switch) would be to use Enumerations instead of arbitrary int values
WestDiscGolf
A: 

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.

Sergio
"Use switch every time you have more than 2 conditions," you should add "on a single variable"
Mehrdad Afshari
agreed, makes quite a difference :)
annakata
Just did that. thanks :)
Sergio
Why? What's the benefit?
Simon
It jsut makes it a little clear that only one condition can be used on a swich
Sergio
A: 

Concerning readability ... I typically prefer if/else constructs over switch statements; especially in languages that allow fall-through cases. What I've found, often, is as projects age, and multiple developers become 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 tossup. 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 contruct (well, until you find the right one, anyway). 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.

A: 

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.

bruno conde
A: 

Lets 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 trying polymorphism instead. 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.

willcodejavaforfood
A: 

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...

Brent.Longborough
But if using a switch statement in languages that allow drop-through, it's better than using redundant code. Say you have a switch testing for days, and you want the same thing to occur on 3 of the days (MWF), you wouldn't want to list the same code 3 times. Better to drop-through or use if/else.
Oh, and I'm not aware of any better optimizations of switches in newer compilers. Do you have examples? Thanks.
A: 

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

Ubersoldat