Writing code that is both functional and easy to read is essential for maintainability and collaboration. Here are five ways to achieve this:
1. Use Parts-of-Speech Naming
Your code should read like a well-crafted story, where every element has a clear, descriptive name. Use nouns for entities like variables, properties, classes, and modules.
Bad Example:
let x = 10;
function calc(a, b) {
return a + b;
}
Good Example:
let userCount = 10;
function calculateTotal(a, b) {
return a + b;
}
2. Keep Functions Small and Focused
Each function should perform a single task and do it well. This makes your code modular, easier to test, and more understandable.
Bad Example:
function handleUserProfile(data) {
// Fetch user
// Validate user data
// Update user profile
// Send confirmation email
}
Good Example:
function fetchUser(id) { /*...*/ }
function validateUserData(data) { /*...*/ }
function updateUserProfile(user) { /*...*/ }
function sendConfirmationEmail(user) { /*...*/ }
3. Consistent Naming Conventions
Use consistent naming conventions throughout your codebase. This helps in reducing cognitive load and makes the code more predictable.
Bad Example:
let user_count = 10;
function CalcTotal(a, b) { /*...*/ }
Good Example:
let userCount = 10;
function calculateTotal(a, b) { /*...*/ }
4. Avoid Deep Nesting
Deep nesting makes code hard to read and maintain. Use early returns to handle error conditions and simplify control flow.
Bad Example:
function processUser(user) {
if (user) {
if (user.isActive) {
// Process active user
}
}
}
Good Example:
function processUser(user) {
if (!user) return;
if (!user.isActive) return;
// Process active user
}
5. Comment Wisely
Comments should explain why something is done, not what is done. Write comments to provide context and reasoning.
Bad Example:
let userCount = 10; // Set userCount to 10
Good Example:
let userCount = 10; // Initial user count for new session
Conclusion
Writing natural code means making it readable, maintainable, and expressive. By using descriptive naming, keeping functions focused, maintaining consistency, avoiding deep nesting, and commenting wisely, you can make your code enjoyable to read and easy to work with. Embrace these practices, and your future self (and teammates) will thank you!
That's all for today.
And also, share your favourite web dev resources to help the beginners here!
Connect with me:@ LinkedIn and checkout my Portfolio.
Explore my YouTube Channel! If you find it useful.
Please give my GitHub Projects a star ⭐️
Thanks for 24821! 🤗
Top comments (2)
Thanks for 24821! 🤗
Some comments may only be visible to logged-in visitors. Sign in to view all comments.