Ever looked at a function and felt lost in its complexity? Let's explore a fundamental principle of clean code: functions should maintain only one level of abstraction.
Here's a real-world example of user creation in a web application:
// ❌ A function doing too many things at different abstraction levels function createUser(userData) { // Validate data if (!userData.email || !userData.email.includes('@')) { return 'Invalid email'; } if (userData.password.lengthThis function mixes different levels of abstraction:
Let's refactor it following the single level of abstraction principle:
// ✅ Clean version with one level of abstraction function createUser(userData) { const validationError = validateUserData(userData); if (validationError) return validationError; const securePassword = hashPassword(userData.password); const formattedUser = formatUserData(userData.email, securePassword); return saveUserToDatabase(formattedUser); } function validateUserData({ email, password }) { if (!email || !email.includes('@')) return 'Invalid email'; if (password.lengthBenefits of This Approach
- Readability: The main function reads like a story, describing what happens at a high level
- Maintainability: Each function has a single responsibility, making changes safer
- Testability: You can test each piece of logic independently
- Reusability: These focused functions can be reused in other contexts
Key Takeaways
When writing functions:
Remember: If you're mixing "how" and "what" in the same function, you're probably dealing with multiple levels of abstraction. Split them up!
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3