If it makes your code harder to read, then it's bad practice.
Whether that's the case in your particular example is up to you to decide, but in general I'd say it probably would be the case.
You asked for alternatives...
Extract some of your code into a sub-function. Eg:
case 'foo' :
myVar = 'blah';
break;
case 'bar' :
myVar = secondLevelFunction();
break;
Here, the secondLevelFunction()
contains the additional switch()
statement where each case
returns a value for myVar
.
Use array mapping. Eg:
var mapper = {'foo':'blah', 'bar':'bibble', etc};
//now, instead of a big switch(input) { .... } block that sets myVar
//for each option, you can just set it directly in a single line, like so:
var myVar = mapper[input];
In addition, if you're looking for concrete measures of code quality, you should learn about Cyclomatic Complexity. This is a measure of how complex a function is. The measurement is taken by looking at how many "decision points" the function has. Each case
, if
, loop, etc is a "decision point". The more you have, the more complex your function.
Cyclomatic Complexity is stronly linked to code quality and good coding practices, so if your function has a high CC score (which it probably will do if it has multiple nested switch
blocks), then it is a sign of poor code quality. Both the alternative solutions I described above can help with this. I'll leave it to you to read up more on CC.
Obviously the alternative solutions would need to be adapted to your needs, but hopefully they give you some ideas.