1. Use Meaningful Names
Principle: Choose names that clearly describe what a variable, function, or class does.
Examples:
- Good:
calculateTotalPrice
,userAge
,fetchData
- Bad:
calc
,x
,data
Explanation: Descriptive names make the code self-explanatory and easier to understand. Avoid single-letter names and vague names that don’t convey purpose.
2. Write Small Functions
Principle: Functions should be small and focused on a single task.
Examples:
- Good:
function printInvoice(invoice) { printHeader(invoice); printDetails(invoice); printFooter(); }
- Bad:
function printInvoice(invoice) { // Code to print header // Code to print details // Code to print footer }
Explanation: Small functions are easier to understand, test, and maintain. Each function should perform one logical task.
3. Avoid Magic Numbers
Principle: Replace unexplained numeric constants with named constants.
Examples:
- Good:
const MAX_USERS = 100; if (userCount > MAX_USERS) { // Handle user limit }
- Bad:
if (userCount > 100) { // Handle user limit }
Explanation: Named constants make the code more readable and easier to modify. Magic numbers can obscure the purpose of the code and lead to errors.
4. Limit the Scope of Variables
Principle: Declare variables in the smallest scope possible.
Examples:
-
Good:
function processOrder(order) { const totalPrice = calculateTotalPrice(order); displayPrice(totalPrice); }
-
Bad:
let totalPrice; function processOrder(order) { totalPrice = calculateTotalPrice(order); displayPrice(totalPrice); }
Explanation: Limiting variable scope helps prevent unintended interactions and makes it easier to track the variable's usage.
5. Use Comments Wisely
Principle: Comments should explain "why" something is done, not "what" is done. Avoid redundant comments.
Examples:
- Good:
// Calculate total price after applying discount const totalPrice = calculateTotalPrice(order) * (1 - discountRate);
- Bad:
const totalPrice = calculateTotalPrice(order); // Calculate total price const discountedPrice = totalPrice * (1 - discountRate); // Apply discount
Explanation: Good comments explain the reasoning behind complex or non-obvious code. Avoid comments that simply restate the code.
6. Avoid Deep Nesting
Principle: Limit the levels of nesting in your code to improve readability.
Examples:
- Good:
if (userIsLoggedIn()) { processUserRequest(); }
- Bad:
if (userIsLoggedIn()) { if (userHasPermission()) { if (requestIsValid()) { processUserRequest(); } } }
Explanation: Deep nesting can make code hard to follow. Refactor complex conditions into separate functions to reduce nesting.
7. Consistent Formatting
Principle: Use consistent code formatting and style throughout your codebase.
Examples:
- Good:
function processOrder(order) { const totalPrice = calculateTotalPrice(order); displayPrice(totalPrice); }
- Bad:
function processOrder(order) { const totalPrice = calculateTotalPrice(order); displayPrice(totalPrice); }
Explanation: Consistent formatting improves readability and makes it easier for others to follow and contribute to the code.
8. Refactor Regularly
Principle: Continuously improve the codebase by refactoring to address code smells and enhance readability.
Examples:
- Good: Regularly revisiting and improving code, breaking down large functions, simplifying complex logic.
- Bad: Ignoring opportunities for improvement and allowing technical debt to accumulate.
Explanation: Refactoring helps maintain code quality and adapt to changing requirements. Regular refactoring prevents code rot and keeps the codebase manageable.
9. Write Tests
Principle: Write automated tests to verify that your code works as expected and to catch regressions.
Examples:
- Good:
function testCalculateTotalPrice() { const order = createOrder(); const result = calculateTotalPrice(order); assert(result === expectedPrice); }
- Bad: No tests or ad-hoc manual testing.
Explanation: Automated tests provide confidence that your code behaves correctly and facilitates safe refactoring.