Writing clean code is an essential skill that every developer should master. Clean code is not just about making your code functional; it’s about making it easy to read, maintain, and extend. Here’s a detailed checklist to help you write clean code:
Use Descriptive and Meaningful Names:
orderTotal
, customerName
.calculateDiscount
, sendEmail
.Invoice
, UserAccount
.Be as Specific as Necessary and Possible: Choose names that clearly convey their purpose and usage.
Use Yes/No “Questions” for Booleans: Name boolean variables as if they answer a yes/no question. Examples: isValid
, hasAccess
.
Avoid Misleading Names: Ensure that names accurately reflect what they represent or do.
Be Consistent with Your Names: Stick to consistent naming conventions throughout the codebase. For instance, if you use get
for retrieval functions, avoid mixing it with fetch
.
Most Comments Are Bad - Avoid Them! Aim to write code that is self-explanatory, reducing the need for comments.
Some Good Comments Are Acceptable:
Use Vertical Formatting:
Use Horizontal Formatting:
Limit the Number of Parameters: Functions should ideally have a small number of parameters. If there are too many, consider grouping them into objects, dictionaries, or arrays.
Functions Should Be Small and Do One Thing:
Stay DRY (Don’t Repeat Yourself): Avoid duplicating code; instead, refactor common code into functions or classes.
Avoid Unexpected Side Effects: Functions should not produce side effects that aren’t apparent from their names or input parameters.
Prefer Positive Checks: Use positive conditions to make code more intuitive.
Avoid Deep Nesting:
Consider Using “Real” Errors: Prefer using exceptions and proper error-handling mechanisms instead of synthetic errors built with if
statements.
Focus on Building “Real Objects” or Data Containers/Structures: Design classes to represent actual entities or structures that encapsulate data and behavior.
Build Small Classes with Single Responsibility: Ensure each class has one clear responsibility, though it may have multiple methods.
Build Classes with High Cohesion: The methods and properties of a class should be closely related and work together towards a common goal.
Follow the “Law of Demeter”: Avoid deep object chains like this.customer.lastPurchase.date
to reduce dependencies and coupling.
Follow SOLID Principles: Especially in object-oriented programming:
By adhering to this checklist, you can write code that is not only functional but also clean, readable, and easy to maintain. Clean code helps in reducing bugs, improving collaboration, and ensuring that your codebase can scale and adapt over time.
Quick Links