DEV Community

Parzival
Parzival

Posted on

The Principle of Least Astonishment (POLA)

Key Concepts

1. Consistent Method Naming

// Bad - Inconsistent naming
class UserManager {
    public function getUser($id) { /* ... */ }
    public function fetchRole($id) { /* ... */ }
    public function retrievePermissions($id) { /* ... */ }
}

// Good - Consistent naming pattern
class UserManager {
    public function getUser($id) { /* ... */ }
    public function getRole($id) { /* ... */ }
    public function getPermissions($id) { /* ... */ }
}
Enter fullscreen mode Exit fullscreen mode

When naming methods, consistency is crucial. In the bad example, we use three different verbs (get, fetch, retrieve) for similar operations. This forces developers to remember different terms for the same type of action. The good example uses 'get' consistently across all methods, making the API more predictable and easier to remember. When developers need to access data, they'll intuitively know to look for a method starting with 'get'.

2. Expected Return Types

// Bad - Unexpected return types
class FileHandler {
    public function readFile($path) {
        if (!file_exists($path)) {
            return false; // Unexpected boolean
        }
        return file_get_contents($path);
    }
}

// Good - Consistent return types with exceptions
class FileHandler {
    public function readFile($path): string {
        if (!file_exists($path)) {
            throw new FileNotFoundException("File not found: {$path}");
        }
        return file_get_contents($path);
    }
}
Enter fullscreen mode Exit fullscreen mode

The bad example mixes return types - sometimes returning a string (file contents) and sometimes a boolean (false). This creates uncertainty about how to handle the return value. The good example ensures type safety by declaring a string return type and using exceptions for error cases. This matches PHP's built-in behavior and makes error handling more explicit and predictable.

3. Predictable Parameter Order

// Bad - Inconsistent parameter order
class OrderProcessor {
    public function createOrder($items, $userId, $date) { /* ... */ }
    public function updateOrder($date, $orderId, $items) { /* ... */ }
}

// Good - Consistent parameter order
class OrderProcessor {
    public function createOrder($userId, $items, $date) { /* ... */ }
    public function updateOrder($orderId, $items, $date) { /* ... */ }
}
Enter fullscreen mode Exit fullscreen mode

Parameter order should be consistent across similar methods. The bad example places similar parameters in different positions, making the API confusing. The good example maintains a logical order: identifier first (userId/orderId), followed by main data (items), and optional/metadata parameters last (date). This pattern matches common conventions in PHP frameworks and makes the API more intuitive.

4. Clear Method Behavior

// Bad - Ambiguous behavior
class Cart {
    public function add($product) {
        // Sometimes creates new item, sometimes updates quantity
        // Unpredictable!
    }
}

// Good - Clear, single responsibility
class Cart {
    public function addNewItem($product) { /* ... */ }
    public function updateQuantity($productId, $quantity) { /* ... */ }
}
Enter fullscreen mode Exit fullscreen mode

Methods should have clear, single responsibilities. The bad example's 'add' method is ambiguous - it might add a new item or update an existing one. The good example splits this into two distinct methods with clear names and purposes. This makes the code's behavior predictable and follows the Single Responsibility Principle (SRP).

5. Consistent Error Handling

class PaymentProcessor {
    public function processPayment(float $amount): PaymentResult {
        try {
            // Process payment
            return new PaymentResult(true, 'Payment successful');
        } catch (PaymentException $e) {
            // Always handle errors the same way
            throw new PaymentFailedException($e->getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This example demonstrates consistent error handling through exceptions. Instead of returning different types or using error codes, it always throws a specific exception type (PaymentFailedException) when something goes wrong. This creates a predictable pattern for error handling across the application. The method also uses a dedicated PaymentResult object for successful cases, maintaining type consistency.

Each of these practices contributes to code that is more maintainable, easier to understand, and less prone to bugs because it behaves in ways that developers expect based on common patterns and conventions in PHP development.

Top comments (0)