Using the Table Lookup Pattern to Replace Conditionals

Today, I want to dive into a powerful design pattern that can make your code cleaner and more maintainable: the table lookup pattern. This pattern is especially useful for replacing long chains of if and switch statements.

The Problem

Let's start with a common scenario. Imagine you have to programmatically determine which payment class to use based on the payment method selected by the user:

$paymentMethod = 'creditCard';

if ($paymentMethod === 'creditCard') {
    $processor = new CreditCardProcessor();
} elseif ($paymentMethod === 'paypal') {
    $processor = new PayPalProcessor();
} elseif ($paymentMethod === 'bankTransfer') {
    $processor = new BankTransferProcessor();
} // ... and so on

Or using a switch statement:

switch ($paymentMethod) {
    case 'creditCard':
        $processor = new CreditCardProcessor();
        break;
    case 'paypal':
        $processor = new PayPalProcessor();
        break;
    case 'bankTransfer':
        $processor = new BankTransferProcessor();
        break;
    // ... and so on
}

While this approach works, it can become cumbersome and hard to maintain as the number of payment method types grow.

The Table Lookup Solution

Instead of using multiple conditional statements, we can use a lookup table (an associative array in PHP) to map user-provided payment methods to their corresponding classes. This way, we can resolve the correct class in a more elegant and scalable manner.

// Define the lookup table
$paymentProcessors = [
    'creditCard' => CreditCardProcessor::class,
    'paypal' => PayPalProcessor::class,
    'bankTransfer' => BankTransferProcessor::class,
    // ... add more mappings as needed
];

// Resolve the payment processor class
if (!array_key_exists($paymentMethod, $paymentProcessors)) {
    // Handle unknown payment method
    throw new Exception("Unknown payment method: $paymentMethod");
}
$processorClass = $paymentProcessors[$paymentMethod];
$processor = new $processorClass();

Benefits

Scalability: Adding a new type is as simple as adding a new entry to the lookup table.
Readability: The code is more concise and easier to understand.
Maintainability: Changes to the logic can be made in one place, reducing the risk of errors.

Conclusion

The table lookup pattern is a powerful tool in a developer's arsenal, especially when dealing with multiple conditional statements. By using this pattern, we can make our PHP code more elegant, readable, and maintainable. So, the next time you find yourself writing long chains of if or switch statements, consider giving the table lookup pattern a try!