views:

67

answers:

2

I inherited a largish JavaScript (MooTools) application for browsing and configuring products.

In it there's a function that tracks the products' configured state. Other functions are called depending on what state the product is in.

I extended it to add some new features, but have ended up with a mess of nested conditionals inside a big switch statement.

My question is, how do you refactor conditional logic? Is there a general (or JS specific) pattern / technique for tracking state?

Update: here's a pseudo-version of the function to illustrate the problem:

switchToVariation: function(link) {

  // set the variables      
  // before switch, set state    

  switch ( nextType ) {   
    case 'type1':
      if ( prevType == 'type1' ) {        
        if ( nextIsSameVariation ) {            
          // do stuff                                           
        } else {                                                                              
          if ( nextIsSomethingElse ) {              
            // do stuff
          }          
          // more stuff                      
        }
      } else {        
        // different stuff        
      }
      break;

    case 'type2':        
      if ( prevWasType1 ) {
        // stuff
      } else {
        if (nextIsSameStyle) {
          // stuff
        }
        // more stuff
      }    
      break;    

    default:                       
      // default stuff        
  }          

  // after switch, set state

}
+2  A: 
T.J. Crowder
this was great advice, thank you! I went for the closures option for now and it's already much easier to follow.
meleyal
@melayal: Excellent, glad that helped! You can gradually keep modularizing on your own schedule (one of the great things about how easy closures are in JS).
T.J. Crowder
+2  A: 

Check out the State pattern.

I wrote an answer explaining it with an example in Java a while back, but it can be easily implemented in JavaScript. It is essentially modeling the system as a finite state machine.

Anurag
Thanks for the pointer, JS.State seems to be a nice implementation:http://jsclass.jcoglan.com/state.html
meleyal