Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java – Force passage from default switch statement

I have a switch where for particular cases I need to do some peculiar things but I still want them to pass through the default case of the switch statement because in there I have functionality that is common to all cases. How can I force the passage to the default case after I’ve handled the peculiar one?

Example:

    switch(someVar) {
        case "a":
            ....
            //do something peculiar for a 
            break;
        case "b":
            ...
            //do something peculiar for b
            break;
        default: 
            ...
            //common things that all cases should do
    }

EDIT: At the moment I’ve just copy-pasted the lines inside the default at the bottom of each peculiar case but that’s ugly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If things must be executed unconditionally, they should be moved out of the condition:

switch(someVar) {
    case "a":
        ....
        //do something peculiar for a 
        break;
    case "b":
        ...
        //do something peculiar for b
        break;
}

//common things that all cases should do

Alternatively, extract a method:

switch(someVar) {
    case "a":
        ....
        //do something peculiar for a 
        doCommonThings();
        break;
    case "b":
        ...
        //do something peculiar for b
        doCommonThings();
        break;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading