Design Patterns: Using Maps to cancel out Switch statements

Posted on July 30, 2011

0


Cancelling out Switch statements

[Removed from other post – requires editing] If you take the code example from “Design Patterns for Dummies”, “Design Patterns” or “C# Design Patterns” and many other resources you will find by default a Switch statement like this:

// The default Switch Statement you find in a lot of code (examples)
Switch ( myValue)
{
   case  SOME_CONSTANT1:
      // Do something if this condition is met
      break;
   case SOME_CONSTANT2:
      // Do something else
      break; 
      // and so on...
   default:
      // capture when no condition is met
}

Or an if/then construction

// Your run of the mill if/then else if you do not switch
if(myValue==SOME_CONSTANT1)
{
   // Do something
}
if(myValue==SOME_CONSTANT2)
{
   // Do something else
}

Instead I (started to consistently) use the following:

// map whatever you want to do on a specific value
public method mapActionToValue(method:Method, myValue:String)
{
   // Map action to value, which is in most cases a constant 
   actionToValueLookopTable[myValue]=method; 
}
// Execute the action we need
public method actOnSpecificConstantValue(myConstantValue:String)
{
   // get the method we mapped to the value
   var myMappedMethod:Method = actionToValueLookupTable[myConstantValue];
   // Exit gracefully if we have no method (or throw an exception)
   if(myMappedMethod==null)
   {
       return "";
   } 
   // Execute the action - internally we know how
   var myReturnValue:String = myMappedMethod() ;
   // Return the result
   return myReturnValue; 
}

The code above is simplified. One thing missing for instance are the sanity checks to assure that the injection and retrieval are not crashing the application due to illegal actions which a specific language does not allow.

Mapping objects, classes and methods

The example above maps Methods to Constants. You are not limited to that, however in most languages. Java, JavaScript, ActionScript and C# allow you to map the following:

  1. References to methods – Allowing you to invoke these methods later, provided that you use the proper number and types of parameters. The reason to avoid this is that you obscure the methods themselves. In contradiction to Objects, you can not always explicitly state what “type” of method you get back from your map.
  2. References to objects – Allowing you to prepare a set of Handlers which deal with the context-specific requests, as we did with our example above.
  3. References to classes – Allowing you to create new objects based on the class, or invoke static methods.

Why mapping is a better approach – in specific cases

  1. Scalability and maintainability – When you expand your library of options, you do not have to add new Switch or If/Then statements. Simply map your (constant) values to your actions and trust your code to execute the proper actions.
  2. Reduction of code – As a project grows, Switch and If/Then/Else statements can grow to hundreds of lines, just to cover all situations.
  3. The possibility to extend your existing lists of options from outside – Using injection. Especially when you build a framework which allows other to add and extend your original code base with extra classes and handlers, your base code does not need a rewrite (as long as they stick to your rules) as each

When mapping is a better approach

  1. If you use a set of specific objects to handle stuff –  For instance to parse data in different ways, or when you want to retrieve a specific view state in your application.
  2. Creation of specific objects based on context or value – If you want to create new objects of a specific type in specific situations, see: “Which patterns benefit directly from mapping”
  3. If you want or need Dynamic lists – For instance to allow the user of your code to create Environments with 3, 5 and 200 colors.

When it is better not to use mapping

  1. If you call methods within your current Class – you will only create code overhead without winning anything.

A list of Design Patterns which benefit directly from mapping

The following Desing Patterns benefit directly from Mapping:

  1. Strategy
  2. Factory
  3. Builder
  4. Interpreter
The Mediator and State Pattern might benefit, but that depends on what they are supposed to do.
Posted in: Design patterns