Legitimate uses for a switch?

by Yada on February 2, 2010

I earned my second “Nice Answer” badge on a Stack Overflow question.  I, myself, don’t find using switch all that useful.  The syntax for switches are always harder to remember compared to chaining a bunch of if else statements.  There are just a few times when switches do come in handy such as finding the number of days in a month.  The answer was well received because it is written in a syntax familiar to all C-like languages.

StackOverflow Question

Switches seem so useless as they can be replaced with if-else statements, which can do much more than just match a char/int/enum etc. I can only think of one good use for a switch, and that would be for interpreting command line args.
What are some realistic uses for a switch statement?

Answer:

There are a few cases where switch is more readable and comes in handy. Usually when you have grouping of options.

Here is one of them:

    int numDays = 0;
    int month = 2;
    int year = 2010;

    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            numDays = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            numDays = 30;
            break;
        case 2:
            if ( ((year % 4 == 0) && !(year % 100 == 0))
                 || (year % 400 == 0) )
                numDays = 29;
            else
                numDays = 28;
            break;
        default:
            System.out.println("Invalid month.");
     }
 

Leave a Comment

Previous post:

Next post:

 

You need to log in to vote

The blog owner requires users to be logged in to be able to vote for this post.

Alternatively, if you do not have an account yet you can create one here.

Powered by Vote It Up