Tired of long and unmaintainable if-elif-elif-else
chains? 😱
Replace them with the "dictionary dispatch pattern", mapping keys to functions. 💡
This makes your code more readable + maintainable because you can easily add new operations without changing the function. 😍 📈
# before
def operation_result(a, b, operation):
if operation == 'add':
return a + b
elif operation == 'subtract':
return a - b
elif operation == 'multiply':
return a * b
elif operation == 'divide':
return a / b
else:
raise ValueError('Unknown operation')
# after
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
OPERATIONS = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide
}
def operation_result(a, b, operation):
if operation not in OPERATIONS:
raise ValueError("Unknown operation")
return OPERATIONS[operation](a, b)
#refactoring