Skip to content

Latest commit

 

History

History
57 lines (39 loc) · 1.1 KB

20240713105037.md

File metadata and controls

57 lines (39 loc) · 1.1 KB

dict dispatch pattern

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. 😍 📈

Related video.

# 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