Home >Backend Development >PHP Tutorial >The Principle of Least Astonishment (POLA)
// 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) { /* ... */ } }
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'.
// 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); } }
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.
// 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) { /* ... */ } }
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.
// 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) { /* ... */ } }
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).
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()); } } }
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!