How to write clean code

June 18, 2024 (10mo ago)

1. Use Meaningful Names

Principle: Choose names that clearly describe what a variable, function, or class does.

Examples:

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:

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:

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:

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:

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:

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:

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:

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:

Explanation: Automated tests provide confidence that your code behaves correctly and facilitates safe refactoring.