Too many if statements

You could possibly use a dictionary. Dictionaries store references, which means functions are perfectly viable to use, like so:

operationFuncs = {
    Operation.START: strategy_objects.StartObject
    Operation.STOP: strategy_objects.StopObject
    Operation.STATUS: strategy_objects.StatusObject
    (...)                  
}

It’s good to have a default operation just in case, so when you run it use a try except and handle the exception (ie. the equivalent of your else clause)

try:
    strategy = operationFuncs[operation]()
except KeyError:
    strategy = strategy_objects.DefaultObject()

Alternatively use a dictionary’s get method, which allows you to specify a default if the key you provide isn’t found.

strategy = operationFuncs.get(operation(), DefaultObject())

Note that you don’t include the parentheses when storing them in the dictionary, you just use them when calling your dictionary. Also this requires that Operation.START be hashable, but that should be the case since you described it as a class similar to an ENUM.

Leave a Comment