user1915747
user1915747

Reputation: 31

Java/C++: possible to have common code for multiple cases in switch?

I find myself running into this situation a lot and was wondering if there are way in Java or C++ or any other language for that matter that allows you to execute code that is common to multiple case statements in a switch but also specialize for individual cases aswell, e.g:

switch(var)
{
   case Preceeding:
   {
       // code executed for both FollowingA and FollowingB
   }
   break;
   case FollowingA:
   {
       // code executed for only FollowingA
   }
   break;
   case FollowingB:
   {
       // code executed for only FollowingB
   }
   break;
}

instead of having to do this:

switch(var)
{
    case FollowingA:
    case FollowingB:
    {
        // code executed for FollowingA and FollowingB
        switch(var)
        {
            case FollowingA:
            {
                // code executed for FollowingA
            }
            break;
            case FollowingB:
            {
                // code executed for FollowingB
            }
            break;
        }
    }
    break;
}

Upvotes: 3

Views: 5983

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129344

It really depends on what you are trying to do - not just from a "can you do this" perspective, but you also have to care for the fact that you or others will have to read and understand the code later.

I typically find that if there are some things that need to be done in more than one case of a switch, it should go into a function (most compilers will inline such code if it's small enough, so there is no performance loss).

So:

 void CommonCode()
 {
    ... 
 }

 switch(var)
 {
    case A:
       CommonCode();
       ... 
       break;
    case B:
       CommonCode();
       ...
       break;
 }

There are however quite a lot of different solutions to this problem, and it really should follow "what is the meaning of what your code does" that should guide how you solve this. Write code that is clear is the primary goal. If that doesn't work, design the code differently. }

Upvotes: 6

Related Questions