General Code Guidelines
Naming Conventions
Section titled “Naming Conventions”Variables and Functions
Section titled “Variables and Functions”// ✅ Good - Clear and descriptiveconst userAge = 25;const calculateTotalPrice = (items) => { ... };
// ❌ Bad - Unclear abbreviationsconst usrAg = 25;const calcTotPrc = (itms) => { ... };
Constants
Section titled “Constants”// ✅ Good - ALL_CAPS for constantsconst MAX_RETRY_ATTEMPTS = 3;const API_BASE_URL = "https://api.example.com";
// ❌ Bad - Inconsistent namingconst maxRetryAttempts = 3;const apibaseurl = "https://api.example.com";
Functions
Section titled “Functions”Keep Functions Small
Section titled “Keep Functions Small”// ✅ Good - Single responsibilityfunction validateEmail(email) { return email.includes("@") && email.includes(".");}
function sendEmail(email, message) { if (!validateEmail(email)) return false; // Send email logic return true;}
// ❌ Bad - Too many responsibilitiesfunction validateAndSendEmail(email, message) { // Validation logic // Email sending logic // Error handling // Logging}
Why this matters: Small functions are easier to test, debug, and reuse. Each function should do one thing well.
Use Descriptive Names
Section titled “Use Descriptive Names”// ✅ Good - Clear intentfunction getUserById(id) { ... }function isValidPassword(password) { ... }
// ❌ Bad - Unclear purposefunction get(id) { ... }function check(pwd) { ... }
Comments
Section titled “Comments”When to Comment
Section titled “When to Comment”// ✅ Good - Explain WHY, not WHAT// Using setTimeout to avoid blocking the UI threadsetTimeout(() => processLargeDataset(), 0);
// Complex business logic explanation// Calculate discount: 10% for new users, 5% for returning usersconst discount = user.isNew ? 0.1 : 0.05;
// ❌ Bad - Obvious comments// Set i to 0let i = 0;
// Add 1 to countercounter++;
Why this matters: Good comments explain the reasoning behind code decisions, not what the code does (which should be obvious from reading it).
Error Handling
Section titled “Error Handling”Always Handle Errors
Section titled “Always Handle Errors”// ✅ Good - Proper error handlingtry { const data = await fetchUserData(userId); return data;} catch (error) { console.error("Failed to fetch user data:", error); throw new Error("User data unavailable");}
// ❌ Bad - Ignoring errorsconst data = await fetchUserData(userId);return data; // What if it fails?
Why this matters: Unhandled errors can crash your application or leave it in an inconsistent state. Always anticipate what can go wrong.
Code Organization
Section titled “Code Organization”Group Related Code
Section titled “Group Related Code”// ✅ Good - Grouped by feature// User validation functionsfunction isValidEmail(email) { ... }function isValidPassword(password) { ... }function validateUser(user) { ... }
// User API functionsfunction createUser(userData) { ... }function updateUser(userId, data) { ... }function deleteUser(userId) { ... }
Use Consistent Indentation
Section titled “Use Consistent Indentation”// ✅ Good - Consistent 2 spacesif (condition) { doSomething(); if (anotherCondition) { doSomethingElse(); }}
// ❌ Bad - Mixed indentationif (condition) { doSomething(); if (anotherCondition) { doSomethingElse(); }}
Best Practices
Section titled “Best Practices”1. Be Consistent
Section titled “1. Be Consistent”- Choose a style and stick to it throughout the project
- Use the same naming patterns everywhere
- Follow team conventions
2. Write Self-Documenting Code
Section titled “2. Write Self-Documenting Code”// ✅ Good - Code explains itselfconst isUserEligibleForDiscount = user.age >= 65 || user.isStudent;
// ❌ Bad - Needs explanationconst eligible = user.age >= 65 || user.isStudent; // What is this for?
3. Avoid Deep Nesting
Section titled “3. Avoid Deep Nesting”// ✅ Good - Early returnsfunction processUser(user) { if (!user) return null; if (!user.isActive) return null; if (!user.hasPermission) return null;
return processActiveUser(user);}
// ❌ Bad - Deep nestingfunction processUser(user) { if (user) { if (user.isActive) { if (user.hasPermission) { return processActiveUser(user); } } } return null;}
4. Don’t Repeat Yourself (DRY)
Section titled “4. Don’t Repeat Yourself (DRY)”// ✅ Good - Reusable functionfunction formatCurrency(amount) { return `$${amount.toFixed(2)}`;}
const totalPrice = formatCurrency(99.99);const discount = formatCurrency(10.0);
// ❌ Bad - Repeated codeconst totalPrice = `$${(99.99).toFixed(2)}`;const discount = `$${(10.0).toFixed(2)}`;
5. Use Meaningful Variable Names
Section titled “5. Use Meaningful Variable Names”// ✅ Good - Intent is clearconst secondsInDay = 24 * 60 * 60;const userRegistrationDate = new Date();
// ❌ Bad - Magic numbers and unclear namesconst x = 24 * 60 * 60; // What is this?const d = new Date(); // Date of what?
6. Favor Composition Over Inheritance
Section titled “6. Favor Composition Over Inheritance”Build functionality by combining simple objects rather than creating complex inheritance hierarchies.
// ✅ Good - Compositionclass EmailService { send(message) { /* implementation */ }}
class User { constructor() { this.emailService = new EmailService(); }
notify(message) { this.emailService.send(message); }}
7. Use Guard Clauses
Section titled “7. Use Guard Clauses”Exit early from functions when conditions aren’t met to reduce nesting.
// ✅ Good - Guard clausesfunction processOrder(order) { if (!order) return null; if (!order.isValid) return null; if (!order.paymentConfirmed) return null;
return executeOrder(order);}
Quick Checklist
Section titled “Quick Checklist”Before committing code, ask yourself:
- Are my variable names descriptive?
- Are my functions doing only one thing?
- Did I handle potential errors?
- Is my code easy to read without comments?
- Am I following the project’s style guide?
- Did I remove debugging statements?
- Are there any magic numbers that should be constants?
- Can someone else understand this code in 6 months?
- Did I test the edge cases?
Universal Principles
Section titled “Universal Principles”These principles apply regardless of programming language:
- KISS (Keep It Simple, Stupid) - Simple solutions are often the best
- YAGNI (You Aren’t Gonna Need It) - Don’t build features you don’t need yet
- Single Responsibility - Each function/class should have one reason to change
- Fail Fast - Detect and report errors as early as possible
Remember: Code is read more often than it’s written!