Is it bad practice to have a switch case in a switch case?

Is it bad practice to have a switch case in a switch case? If so, what are alternatives? I don't really want to use if / else if if I don't need.

Instead of doing some like:

if((this == 1) && (that == 1)){ //something }
else if((this == 1) && (that == 2)){ //something }
else if((this == 2) && (that == 3)){ //something }

I was thinking along the lines of:

switch(this){
    case 1:
        switch(that){
            case 1:
                // something
            break;
            ....
        }
    break;
    ....
}

It just looks really wrong to me. Not wrong in syntax but wrong in terms of proper practice.


Avoid following approach

switch(id)
{
    case 1:
    {
        switch (subid)
        {
            case 4:
                // nested code
        }
    }
    case 2:
         // some code
}

The preferable approach and improve your code by moving nested section into a method

switch(id)
{
    case 1:
        SubSwtich(subid);
        break;
    case 2:
         // some code
}

function SubSwtich(int subid)
{
        switch (subid)
        {
            case 4:
                // nested code
        }
}

It's bad practise to have massive functions that do lots of different things. If you have a switch case in a switch case, that suggests your function is probably too big and you should consider splitting it up into smaller easier-to-understand chunks.

But there are no hard-and-fast rules; it all depends on the exact scenario.


i would consider it a bad pratice. in most cases this is unreadable.

you can extract the "sub" switch-cases to methods.

链接地址: http://www.djcxy.com/p/51986.html

上一篇: 重载与重写在JavaScript中

下一篇: 在开关盒中安装开关盒是不好的做法吗?