Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice with javascript switch statement

I'm currently working on a jquery script using the switch statement and I was wondering what was the best solution when several 'cases' share some properties, let's say I have this pattern:

switch (settings.xxx) {
case 'case1':
    Execute some code
    break;
case 'case2':
    Execute some code
    break;
case 'case3':
    Execute some code
    break;
}

For each case, I have quite a lot of code that's partly repeated because some properties are common to the 3 cases. So my question is, can I do the same with :

switch (settings.xxx) {

case 'case1':
case 'case2':
case 'case3':
    Execute some code
    break;

}

switch (settings.xxx) {

case 'case1':
case 'case2':
    Execute some code
    break;
case 'case2':
case 'case3':
    Execute some code
    break;

}

Or is it a bad practice?

like image 612
user1854123 Avatar asked Nov 26 '12 17:11

user1854123


2 Answers

No, it's not bad practice. Actually, it is good practice. This way, you would not repeat yourself.

Also, take a look at the documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/switch

like image 149
Adriano Carneiro Avatar answered Oct 02 '22 14:10

Adriano Carneiro


The best practice is to avoid repeating code. That way if you later need to modify the code, you don't need to remember to do it in multiple places.

In the situation where some of the code only applies to some cases, you can leave out a break, and the execution will fall through to the next section after executing the first section. This only applies when the special case code can be executed before the general case code. Be careful when you do this, and add comments clearly stating that you are doing it intentionally. Otherwise, if the code is later edited, someone else might not realise that it is intentional, and add the break in where it is missing. See below:

switch (settings.xxx) {
case 'case1':
case 'case2':
    Execute some code that applies to cases 1 & 2
    // break left out to allow execution to fall through
case 'case3':
    Execute some code that applies to cases 1 - 3
    break;
case 'case4':
    Execute different code
    break;
}
like image 44
Eric Kent Avatar answered Oct 02 '22 12:10

Eric Kent