toweddeji-2389 toweddeji-2389 - 3 months ago 16
Java Question

How to minimize switch statement?

I am using switch statement to handle over 20 cases. It there a way to minimize a long switch statement for e.g as given below:

switch (something) {

case 1:
doX();
break;

case 2:
doY();
break;

case 3:
doN();
break;

// And so on...

}

Answer

You have provide only a pseudo-code. You should have provide your actual code so that I may have guided you better. Anyhow you may use the following short form for your long swith statement.

var cases = {
    1: doX,
    2: doY,
    3: doN
    //......................cases from 4 to 19
    20: doZ
};
if (cases[something]) {
    cases[something]();
}

Hope it helps.

Comments