views:

162

answers:

3

What is the best way to reuse switch logic. I have this switch statement that keeps appearing in my code. Rather then copy paste it I would like to make a function that calls other delegates and pass these delegates in as parameters.

Or is there a better way?

Function 1:

switch (test)
        {
            case "x":
                DoSomethingX();
                break;
            case "y":
                DoSomethingY();
                break;
            case "z":
                DoSomethingZ();
                break;
        }

Function 2:

switch (test)
    {
        case "x":
            DoSomethingXxxx();
            break;
        case "y":
            DoSomethingYyyy();
            break;
        case "z":
            DoSomethingZyyy();
            break;
    }
+9  A: 

You could also have a Dictionary (or Func instead of Action) or something like that (considering your functions have a similar signature). Then you could instead of using a switch, you could have something like:

public class MyClass
{
    Dictionary<string, Action> myDictionary;

    public MyClass()
    {
        BuildMyDictionary();
    }

    private Dictionary<int, Action<int, int>> BuildMyDictionary()
    {
        myDictionary.Add("x", DoSomethingX);
        myDictionary.Add("y", DoSomethingY);
        myDictionary.Add("z", DoSomethingZ);
        myDictionary.Add("w", DoSomethingW);
    }


    public void DoStuff()
    {
        string whatever = "x"; //Get it from wherever
        //instead of switch
        myDictionary[t]();
    }
}

I answered a similar question here with a similar example.

Also, try using enums instead of strings in your switch statement.

Samuel Carrijo
+1 for Table-driven methods ch.18 of Code Complete
Lucas B
+4  A: 

See if you can refactor this using an interface and different implementations of the interface.

public interface Test {
    void DoSomething();
}

public class TestX : Test {
    void DoSomething() {
    }
}

public class TestY : Test {
    void DoSomething() {
    }
}

public class TestZ : Test {
    void DoSomething() {
    }
}


void func(Test test) {
    test.DoSomething();
}
Jared Oberhaus
*sigh* You beat me to that one! Was almost done even :p
Svish
Sorry @Svish, I'm sure you'll beat me next time. It's happened before. :)
Jared Oberhaus
A: 

As I try to understand your question, I might go to following:

public enum Test{
    X, Y, Z
}

/**
* test function call 
* @a_Test - enumeration class for Test
*/
public void test(Test a_Test){
 switch(a_Test){
   case X:
       x();
       break;
   case Y:
       y();
       break;
   case Z:
       z();
       break;
 }//switch
}//test

I hope it helps.

Tiger

Tiger