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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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)