Dans le développement de logiciels, le respect de pratiques de code propre est essentiel pour créer des applications maintenables, évolutives et efficaces. Une approche qui encourage cette discipline est l'Object Calisthenics, un ensemble de règles conçues pour guider les développeurs dans l'écriture d'un meilleur code orienté objet.
Dans cet article, j'explorerai les principes de la callisthénie des objets et comment ils peuvent être appliqués pour écrire du code plus propre et plus structuré. Si vous souhaitez approfondir des exemples de code pratiques ou apprendre comment ces principes sont mis en œuvre dans un projet réel, n'hésitez pas à consulter mon référentiel GitHub pour plus de détails.
Pour une explication plus pratique, visitez mon référentiel GitHub.
Object Calisthenics est un exercice de programmation composé de neuf règles qui vous encouragent à adhérer aux principes orientés objet. Les règles elles-mêmes ont été introduites par Jeff Bay dans son livre The ThoughtWorks Anthology. L'objectif est d'encourager une concentration plus approfondie sur la conception et la structure de votre code en suivant ces contraintes.
Voici les 9 règles :
Ce principe stipule que chaque méthode ne doit avoir qu'un seul niveau d'indentation. En gardant le niveau d'indentation faible, nous pouvons améliorer la lisibilité et rendre le code plus facile à maintenir. Si une méthode comporte trop de niveaux d’indentation, c’est souvent le signe que la logique interne est trop complexe et doit être décomposée en éléments plus petits.
Exemple de mise en œuvre
Voici un exemple de méthode qui ne suit pas ce principe :
public class OrderService { public void processOrder(Order order) { if (order.isValid()) { if (order.hasStock()) { if (order.hasEnoughBalance()) { order.ship(); } else { System.out.println("Insufficient balance."); } } else { System.out.println("Stock unavailable."); } } else { System.out.println("Invalid order."); } } }
Dans le code ci-dessus, il existe plusieurs niveaux d'indentation dans la méthode processOrder, ce qui rend la lecture plus difficile, surtout lorsque la logique devient plus complexe.
Voyons maintenant comment on peut suivre le principe en simplifiant la logique :
public class OrderService { public void processOrder(Order order) { if (!isOrderValid(order)) return; if (!hasStock(order)) return; if (!hasEnoughBalance(order)) return; shipOrder(order); } private boolean isOrderValid(Order order) { if (!order.isValid()) { System.out.println("Invalid order."); return false; } return true; } private boolean hasStock(Order order) { if (!order.hasStock()) { System.out.println("Stock unavailable."); return false; } return true; } private boolean hasEnoughBalance(Order order) { if (!order.hasEnoughBalance()) { System.out.println("Insufficient balance."); return false; } return true; } private void shipOrder(Order order) { order.ship(); } }
Cette version a un niveau d'indentation par bloc logique, ce qui rend le code plus propre et plus facile à maintenir.
Dans la programmation orientée objet, l'utilisation du mot-clé else conduit souvent à un code encombré et difficile à maintenir. Au lieu de vous fier aux instructions else, vous pouvez structurer votre code à l'aide de retours précoces ou de polymorphisme. Cette approche améliore la lisibilité, réduit la complexité et rend votre code plus maintenable.
Regardons d'abord un exemple qui utilise le mot-clé else :
public class Order { public void processOrder(boolean hasStock, boolean isPaid) { if (hasStock && isPaid) { System.out.println("Order processed."); } else { System.out.println("Order cannot be processed."); } } }
Dans cet exemple, l'instruction else nous oblige à gérer explicitement le cas négatif, ce qui ajoute une complexité supplémentaire. Maintenant, refactorisons ceci pour éviter d'utiliser else :
public class Order { public void processOrder(boolean hasStock, boolean isPaid) { if (!hasStock) { System.out.println("Order cannot be processed: out of stock."); return; } if (!isPaid) { System.out.println("Order cannot be processed: payment pending."); return; } System.out.println("Order processed."); } }
En éliminant else, vous écrivez un code plus ciblé, chaque section gérant une seule responsabilité. Cela correspond au « principe de responsabilité unique » et contribue à créer des logiciels plus propres et plus maintenables.
L'une des pratiques clés de Object Calisthenics consiste à envelopper toutes les primitives et chaînes dans des classes personnalisées. Cette règle encourage les développeurs à éviter d'utiliser des types primitifs bruts ou des chaînes directement dans leur code. Au lieu de cela, ils devraient les encapsuler dans des objets significatifs. Cette approche conduit à un code plus expressif, plus facile à comprendre et pouvant gagner en complexité sans devenir ingérable.
Considérons un exemple où nous utilisons directement des types primitifs et des chaînes :
public class Order { private int quantity; private double pricePerUnit; private String productName; public Order(int quantity, double pricePerUnit, String productName) { this.quantity = quantity; this.pricePerUnit = pricePerUnit; this.productName = productName; } public double calculateTotal() { return quantity * pricePerUnit; } }
Dans ce code, int, double et String sont utilisés directement. Bien que cela puisse paraître simple, cela n'exprime pas clairement l'intention de chaque valeur et rend plus difficile l'introduction ultérieure de nouveaux comportements ou contraintes spécifiques à ces valeurs.
Maintenant, refactorisons ce code pour envelopper les primitives et les chaînes :
public class Quantity { private final int value; public Quantity(int value) { if (value < 1) { throw new IllegalArgumentException("Quantity must be greater than zero."); } this.value = value; } public int getValue() { return value; } } public class Price { private final double value; public Price(double value) { if (value <= 0) { throw new IllegalArgumentException("Price must be positive."); } this.value = value; } public double getValue() { return value; } } public class ProductName { private final String name; public ProductName(String name) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Product name cannot be empty."); } this.name = name; } public String getValue() { return name; } } public class Order { private final Quantity quantity; private final Price pricePerUnit; private final ProductName productName; public Order(Quantity quantity, Price pricePerUnit, ProductName productName) { this.quantity = quantity; this.pricePerUnit = pricePerUnit; this.productName = productName; } public double calculateTotal() { return quantity.getValue() * pricePerUnit.getValue(); } }
Changements clés :
Chaque fois que vous utilisez une collection comme une liste ou une carte, faites-en un objet dédié. Cela garde votre code propre et garantit que la logique liée à la collection est encapsulée.
Problem: Using a Raw Collection Directly
public class Order { private List<String> items; public Order() { this.items = new ArrayList<>(); } public void addItem(String item) { items.add(item); } public List<String> getItems() { return items; } }
In this example, Order directly uses a List
Solution: Using a First-Class Collection
public class Order { private Items items; public Order() { this.items = new Items(); } public void addItem(String item) { items.add(item); } public List<String> getItems() { return items.getAll(); } } class Items { private List<String> items; public Items() { this.items = new ArrayList<>(); } public void add(String item) { items.add(item); } public List<String> getAll() { return new ArrayList<>(items); // Return a copy to prevent external modification } public int size() { return items.size(); } }
Explanation:
Benefits of First-Class Collections:
One Dot Per Line is an Object Calisthenics rule that encourages developers to avoid chaining multiple method calls on a single line. The principle focuses on readability, maintainability, and debugging ease by ensuring that each line in the code only contains a single method call (represented by one "dot").
The Problem with Method Chaining (Multiple Dots Per Line)
When multiple methods are chained together on one line, it can become difficult to:
Example: Multiple Dots Per Line (Anti-Pattern)
public class OrderProcessor { public void process(Order order) { String city = order.getCustomer().getAddress().getCity().toUpperCase(); } }
In this example, we have multiple method calls chained together (getCustomer(), getAddress(), getCity(), toUpperCase()). This makes the line of code compact but harder to understand and maintain.
Solution: One Dot Per Line
By breaking down the method chain, we make the code easier to read and debug:
public class OrderProcessor { public void process(Order order) { Customer customer = order.getCustomer(); // One dot: getCustomer() Address address = customer.getAddress(); // One dot: getAddress() String city = address.getCity(); // One dot: getCity() String upperCaseCity = city.toUpperCase(); // One dot: toUpperCase() } }
This code follows the One Dot Per Line rule by breaking down a method chain into smaller, readable pieces, ensuring that each line performs only one action. This approach increases readability, making it clear what each step does, and improves maintainability by making future changes easier to implement. Moreover, this method helps during debugging, since each operation is isolated and can be checked independently if any errors occur.
In short, the code emphasizes clarity, separation of concerns, and ease of future modifications, which are key benefits of applying Object Calisthenics rules such as One Dot Per Line.
One of the key rules in Object Calisthenics is Don’t Abbreviate, which emphasizes clarity and maintainability by avoiding cryptic or shortened variable names. When we name variables, methods, or classes, it’s important to use full, descriptive names that accurately convey their purpose.
Example of Bad Practice (With Abbreviations):
public class EmpMgr { public void calcSal(Emp emp) { double sal = emp.getSal(); // Salary calculation logic } }
Example of Good Practice (Without Abbreviations):
public class EmployeeManager { public void calculateSalary(Employee employee) { double salary = employee.getSalary(); // Salary calculation logic } }
By avoiding abbreviations, we make our code more understandable and maintainable, especially for other developers (or even ourselves) who will work on it in the future.
In Object Calisthenics, one of the fundamental rules is Keep Entities Small, which encourages us to break down large classes or methods into smaller, more manageable ones. Each entity (class, method, etc.) should ideally have one responsibility, making it easier to understand, maintain, and extend.
Example of Bad Practice (Large Class with Multiple Responsibilities):
public class Employee { private String name; private String address; private String department; public void updateAddress(String newAddress) { this.address = newAddress; } public void promote(String newDepartment) { this.department = newDepartment; } public void generatePaySlip() { // Logic for generating a payslip } public void calculateTaxes() { // Logic for calculating taxes } }
In this example, the Employee class is doing too much. It’s handling address updates, promotions, payslip generation, and tax calculation. This makes the class harder to manage and violates the Single Responsibility Principle.
Example of Good Practice (Small Entities with Single Responsibilities):
public class Employee { private String name; private String address; private String department; public void updateAddress(String newAddress) { this.address = newAddress; } public void promote(String newDepartment) { this.department = newDepartment; } } public class PaySlipGenerator { public void generate(Employee employee) { // Logic for generating a payslip for an employee } } public class TaxCalculator { public double calculate(Employee employee) { // Logic for calculating taxes for an employee return 0.0; } }
By breaking the class into smaller entities, we:
The principle of avoiding getters and setters encourages encapsulation by ensuring that classes manage their own data and behavior. Instead of exposing internal state, we should focus on providing meaningful methods that perform actions relevant to the class's responsibility.
Consider the following example that uses getters and setters:
public class BankAccount { private double balance; public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { if (amount <= balance) { balance -= amount; } } }
In this example, the getBalance method exposes the internal state of the BankAccount class, allowing direct access to the balance variable.
A better approach would be to avoid exposing the balance directly and provide methods that represent the actions that can be performed on the account:
public class BankAccount { private double balance; public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { if (amount <= balance) { balance -= amount; } } public boolean hasSufficientFunds(double amount) { return amount <= balance; } }
In this revised example, the BankAccount class no longer has getters or setters. Instead, it provides methods for depositing, withdrawing, and checking if there are sufficient funds. This approach maintains the integrity of the internal state and enforces rules about how the data can be manipulated, promoting better encapsulation and adherence to the single responsibility principle.
The principle of separating user interface (UI) code from business logic is essential for creating maintainable and testable applications. By keeping these concerns distinct, we can make changes to the UI without affecting the underlying business rules and vice versa.
Consider the following example where the UI and business logic are intertwined:
public class UserRegistration { public void registerUser(String username, String password) { // UI Logic: Validation if (username.isEmpty() || password.length() < 6) { System.out.println("Invalid username or password."); return; } // Business Logic: Registration System.out.println("User " + username + " registered successfully."); } }
In this example, the registerUser method contains both UI logic (input validation) and business logic (registration). This makes the method harder to test and maintain.
A better approach is to separate the UI from the business logic, as shown in the following example:
public class UserRegistration { public void registerUser(User user) { // Business Logic: Registration System.out.println("User " + user.getUsername() + " registered successfully."); } } public class UserRegistrationController { private UserRegistration userRegistration; public UserRegistrationController(UserRegistration userRegistration) { this.userRegistration = userRegistration; } public void handleRegistration(String username, String password) { // UI Logic: Validation if (username.isEmpty() || password.length() < 6) { System.out.println("Invalid username or password."); return; } User user = new User(username, password); userRegistration.registerUser(user); } } class User { private String username; private String password; public User(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } }
In this improved design, the UserRegistration class contains only the business logic for registering a user. The UserRegistrationController is responsible for handling UI logic, such as input validation and user interaction. This separation makes it easier to test and maintain the business logic without being affected by changes in the UI.
By adhering to this principle, we enhance the maintainability and testability of our applications, making them easier to adapt to future requirements.
Object Calisthenics might seem a bit strict at first, but give it a try! It's all about writing cleaner, more maintainable code that feels good to work with. So, why not challenge yourself? Start small, and before you know it, you’ll be crafting code that not only works but also shines. Happy coding!
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!