Using the Switch Statement

If the expression on which your conditional logic depends may take on many different values, and for each different value you'd like a different block of code to execute, use the switch statement to simplify the task.

As shown in the example below, the expression passed as the single argument to the switch statement is compared with the value in each case block. The code inside the first matching case block will execute. Notice the use of the break statement inside of each case block. Failure to include this break statement results in the execution of code from subsequent case blocks, which will typically lead to bugs in your application.

Notice, further, that in addition to using a specific value like 'A' or 'B' you can also use a range of values like 'C'..'P' or a list of values like ['Q','X','Z']. The switch expression is not restricted to being a string as is used in this example; it can be any object type.

def logMsg
def maxDiscount = 0
// warehouse code is first letter of product SKU
// uppercase the letter before using it in switch
def warehouseCode = upperCase(left(SKU,1))
// Switch on warehouseCode to invoke appropriate
// object function to calculate max discount
switch (warehouseCode) {
  case 'A': 
    maxDiscount = Warehouse_A_Discount()
    logMsg = 'Used warehouse A calculation'
    break
  case 'B':
    maxDiscount = Warehouse_B_Discount()
    logMsg = 'Used warehouse B calculation'
  case 'C'..'P':
    maxDiscount = Warehouse_C_through__P_Discount()
    logMsg = 'Used warehouse C-through-P calculation'
    break    
  case ['Q','X','Z']: 
    maxDiscount = Warehouse_Q_X_Z_Discount()
    logMsg = 'Used warehouse Q-X-Z calculation'
    break
  default:
    maxDiscount = Default_Discount()
    logMsg = 'Used default max discount'
}
println(logMsg+' ['+maxDiscount+']')
// return expression that will be true when rule is valid
return Discount == null || Discount <= maxDiscount