DEV Community

Cover image for Clean code: principle and best practice
zonaetmunna
zonaetmunna

Posted on

Clean code: principle and best practice

Clean code is a concept that refers to writing code in such a way that it is easy to understand, easy to maintain, and easy to modify. The principles and best practices for writing clean code can be summarized as follows:

1. Meaningful Names:

  • Use descriptive, unambiguous names for variables, functions, classes, and modules.
  • Avoid disinformation (e.g., using a variable name l that looks like 1 or I).
  • Make meaningful distinctions (e.g., getUserInfo vs getUserData).
  • Use pronounceable names.

2. Functions:

  • Functions should be small and do only one thing.
  • They should have a small number of parameters, ideally no more than three.
  • Function names should describe what they do.
  • Functions should not have side effects that are not obvious from the name.

3. Comments:

  • Comments should explain why something is done, not what is done.
  • Avoid redundant comments that just repeat the code.
  • Update comments when code changes.
  • Use comments to mark incomplete code or areas that need improvement.

4. Formatting:

  • Code should be consistently indented and formatted.
  • Use blank lines to separate sections of code that are logically related.
  • Follow the coding standards of your team or organization.

5. Error Handling:

  • Use exceptions rather than return codes for error handling.
  • Don't ignore exceptions.
  • Provide context with exceptions to make them more helpful.

6. Unit Tests:

  • Write tests for your code.
  • Tests should be clean, too – easy to read, easy to understand, and easy to modify.
  • Tests should cover various cases and edge conditions.

7. DRY (Don't Repeat Yourself):

  • Avoid duplication of code.
  • Use abstraction, functions, or classes to avoid code duplication.

8. Simplicity:

  • Write simple code that gets the job done.
  • Avoid over-engineering and premature optimization.
  • Remove unnecessary code.

9. Code Review:

  • Regularly review your code with colleagues to catch mistakes and get suggestions for improvement.

10. Refactoring:

  • Continuously refactor your code to make it cleaner.
  • Make one change at a time and test it before moving on.

11. Code Cohesion:

  • Keep related code together.
  • Ensure that classes and modules have a clear responsibility.

12. Use Design Patterns Wisely:
Use design patterns where they are needed, but don't force them into your code.

15. Code Documentation:
Write documentation that explains how to use your code, especially for libraries and APIs.

Top comments (0)