Home > Backend Development > PHP Tutorial > The Principle of Least Astonishment (POLA)

The Principle of Least Astonishment (POLA)

Linda Hamilton
Release: 2024-12-13 13:21:11
Original
877 people have browsed it

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) { /* ... */ }
}
Copy after login

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);
    }
}
Copy after login

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) { /* ... */ }
}
Copy after login

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) { /* ... */ }
}
Copy after login

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());
        }
    }
}
Copy after login

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.

The above is the detailed content of The Principle of Least Astonishment (POLA). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template