Home >Web Front-end >JS Tutorial >The Golden Rule of Clean Code: Functions Should Do One Thing
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!
The above is the detailed content of The Golden Rule of Clean Code: Functions Should Do One Thing. For more information, please follow other related articles on the PHP Chinese website!