Maison > Article > interface Web > La règle d'or du code propre : les fonctions doivent faire une chose
In the world of software engineering, there's one principle that stands above the rest: Functions should do one thing, and do it well. This concept, often referred to as the Single Responsibility Principle (SRP), is a cornerstone of clean, maintainable code.
When functions have a single responsibility:
Let's look at an example to illustrate this principle in action.
Consider this function that emails clients:
function emailClients(clients) { clients.forEach(client => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); } }); }
This function is doing several things:
While it might seem efficient to have all this in one place, it makes the function harder to maintain and test.
Now, let's refactor this into smaller, focused functions:
function emailActiveClients(clients) { clients.filter(isActiveClient).forEach(email); } function isActiveClient(client) { const clientRecord = database.lookup(client); return clientRecord.isActive(); }
In this refactored version:
This separation of concerns makes each function easier to understand, test, and potentially reuse in other parts of your codebase.
Embracing the "Functions should do one thing" principle might feel verbose at first, but the long-term benefits to your codebase's maintainability and your team's productivity are immense. As you write and refactor code, always ask yourself: "Is this function doing more than one thing?" If the answer is yes, it's time to break it down!
Remember, clean code isn't just about making things work—it's about making things work elegantly and sustainably. 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!