Question

I have below switch case in my code.

   switch(condition)
       case 'A' :   
        //Code part A
        break;
       case 'B' :   
        //Code part A
        //Code part B
        break;
       case 'C' :   //Some code
        break;

code Part A is repeated in both case 'A' and case 'B'. I want to avoid duplication of code.

If we use fall though then we need to add an if condition for case B. Is this the only way for avoiding repetition of code?

Was it helpful?

Solution

If the order is not important, you can simply do:

switch (condition)
{
    case 'B':
        // Code part B
        // no break
    case 'A':
        // Code part A
        break;
    ...
}

A case 'B' will continue to execute through the case 'A' code because you didn't call a break.

OTHER TIPS

Manipulating a switch statement to reduce duplication of code may work at first, but then you may add additional cases to the switch later, which may break that cleanness of that optimization. For example:

   switch(condition)

       case 'A' :   
        // Code part A
        break;

       case 'B' :   
        // Code part A
        // Code part B
        break;

       case 'C' :   
        // Code part C
        break;

       case 'D' :
        // Code part A
        // Code part D
        break;

Suddenly an optimization which seemed nice at the time, starts to become difficult to maintain, difficult to read and error prone.

Having already determined that there is common code, the cleanest response in my view is to write functions to perform the common code and call from each case. Going forward, this will continue to be maintainable.

Unfortunately, that's the only way, short of defining a function for partA.

You can reduce nesting by exiting the switch from inside the combined case label to make the code look a little more uniform:

switch (someValue) {
    case 'A':
    case 'B':
        // Code part A
        if (someValue == 'A') break;
        // Code part B
        break;
    case 'C':
        break;
}

This lets your part A and part B code have the same level of nesting.

Can "//Code part B" be executed before "//Code part A"? If so, you could just reorder them and let it fall through without an if condition.

I don't think there's much else to do, otherwise. One of the reasons for the creation of object-oriented languages was avoiding the duplication of code you have in imperative languages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top