What's the best alternative to an out of control switch statement?

后端 未结 11 1421
悲&欢浪女
悲&欢浪女 2021-02-14 14:20

I have inherited a project that has some huge switch statement blocks, with some containing up to 20 cases. What is a good way to rewrite these?

11条回答
  •  孤街浪徒
    2021-02-14 14:58

    As others have pointed out, it depends on the switch statement. However, in the past I have refactored switch statements by proceeding in the following way. Suppose we have a switch statement like this, with a lot of repeating code

    switch(x){
       case 1:
         makeitso("foo");
         globalLog += "foo";
       case 2:
         makeitso("bar");
         globalLog += "bar";
       case 3:
         makeitso("baz");
         globalLog += "baz";
       ...
       default:
          throw("input error");
    }
    

    the first thing to do is to recognize the parts that are common (in the real world, this will probably be a little more substantial)

    makeitso([some string]);
    globalLog += [some string];
    

    and turn that into a function

    function transformInput(somestring) {
         makeitso(somestring);
         globalLog += somestring;
    }
    

    then for the parts that change in each case, use a hash or an array;

    var transformvalues = ["foo", "bar", "baz"];
    

    from here we can do this:

    var tvals = ["foo", "bar", "baz" ... ];
    function transformInput(somestring) {
         makeitso(somestring);
         globalLog += somestring;
    }
    var tval = tvals[x];
    if(tval!==undefined) {
         transformInput(tval);
    } else {
        throw ("invalid input");
    } 
    

    And with tvals factored out of the switch statement, it could even be provided externally to expand the number of cases you can handle. Or you could build it dynamically. In the real world, the switch statement will often have special cases, however. I leave that as an excercise for the reader.

提交回复
热议问题