Writing code is like giving a speech. If you use too many big words, you confuse your audience. Define every word, and you end up putting your audience to sleep. Similarly, when you write code, you shouldn't just focus on making it work. You should also aim to make it readable, understandable, and maintainable for future readers. To paraphrase software engineer Martin Fowler, "Anybody can write code that a computer can understand. Good programmers write code that humans can understand."
Add this skill
npx mdskills install PatrickJS/cursor-githubEducational article on clean code principles, not actionable agent instructions
1Writing code is like giving a speech. If you use too many big words, you confuse your audience. Define every word, and you end up putting your audience to sleep. Similarly, when you write code, you shouldn't just focus on making it work. You should also aim to make it readable, understandable, and maintainable for future readers. To paraphrase software engineer Martin Fowler, "Anybody can write code that a computer can understand. Good programmers write code that humans can understand."23As software developers, understanding how to write clean code that is functional, easy to read, and adheres to best practices helps you create better software consistently.45This article discusses what clean code is and why it's essential and provides principles and best practices for writing clean and maintainable code.67What Is Clean Code?89Clean code is a term used to refer to code that is easy to read, understand, and maintain. It was made popular by Robert Cecil Martin, also known as Uncle Bob, who wrote "Clean Code: A Handbook of Agile Software Craftsmanship" in 2008. In this book, he presented a set of principles and best practices for writing clean code, such as using meaningful names, short functions, clear comments, and consistent formatting.1011Ultimately, the goal of clean code is to create software that is not only functional but also readable, maintainable, and efficient throughout its lifecycle.1213Why Is Clean Code Important?1415When teams adhere to clean code principles, the code base is easier to read and navigate, which makes it faster for developers to get up to speed and start contributing. Here are some reasons why clean code is essential.1617Readability and maintenance: Clean code prioritizes clarity, which makes reading, understanding, and modifying code easier. Writing readable code reduces the time required to grasp the code's functionality, leading to faster development times.1819Team collaboration: Clear and consistent code facilitates communication and cooperation among team members. By adhering to established coding standards and writing readable code, developers easily understand each other's work and collaborate more effectively.2021Debugging and issue resolution: Clean code is designed with clarity and simplicity, making it easier to locate and understand specific sections of the codebase. Clear structure, meaningful variable names, and well-defined functions make it easier to identify and resolve issues.2223Improved quality and reliability: Clean code prioritizes following established coding standards and writing well-structured code. This reduces the risk of introducing errors, leading to higher-quality and more reliable software down the line.2425Now that we understand why clean code is essential, let's delve into some best practices and principles to help you write clean code.2627Principles of Clean Code2829Like a beautiful painting needs the right foundation and brushstrokes, well-crafted code requires adherence to specific principles. These principles help developers write code that is clear, concise, and, ultimately, a joy to work with.3031Let's dive in.32331. Avoid Hard-Coded Numbers3435Use named constants instead of hard-coded values. Write constants with meaningful names that convey their purpose. This improves clarity and makes it easier to modify the code.3637Example:3839The example below uses the hard-coded number 0.1 to represent a 10% discount. This makes it difficult to understand the meaning of the number (without a comment) and adjust the discount rate if needed in other parts of the function.4041Before:4243def calculate_discount(price):44 discount = price * 0.1 # 10% discount45 return price - discount4647The improved code replaces the hard-coded number with a named constant TEN_PERCENT_DISCOUNT. The name instantly conveys the meaning of the value, making the code more self-documenting.4849After:5051def calculate_discount(price):52 TEN_PERCENT_DISCOUNT = 0.153 discount = price * TEN_PERCENT_DISCOUNT54 return price - discount5556Also, If the discount rate needs to be changed, it only requires modifying the constant declaration, not searching for multiple instances of the hard-coded number.57582. Use Meaningful and Descriptive Names5960Choose names for variables, functions, and classes that reflect their purpose and behavior. This makes the code self-documenting and easier to understand without extensive comments. As Robert Martin puts it, “A name should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.”6162Example:6364If we take the code from the previous example, it uses generic names like "price" and "discount," which leaves their purpose ambiguous. Names like "price" and "discount" could be interpreted differently without context.6566Before:6768def calculate_discount(price):69 TEN_PERCENT_DISCOUNT = 0.170 discount = price * TEN_PERCENT_DISCOUNT71 return price - discount7273Instead, you can declare the variables to be more descriptive.7475After:7677def calculate_discount(product_price):78 TEN_PERCENT_DISCOUNT = 0.179 discount_amount = product_price * TEN_PERCENT_DISCOUNT80 return product_price - discount_amount8182This improved code uses specific names like "product_price" and "discount_amount," providing a clearer understanding of what the variables represent and how we use them.83843. Use Comments Sparingly, and When You Do, Make Them Meaningful8586You don't need to comment on obvious things. Excessive or unclear comments can clutter the codebase and become outdated, leading to confusion and a messy codebase.8788Example:8990Before:9192def group_users_by_id(user_id):93 # This function groups users by id94 # ... complex logic ...95 # ... more code …9697The comment about the function is redundant and adds no value. The function name already states that it groups users by id; there's no need for a comment stating the same.9899Instead, use comments to convey the "why" behind specific actions or explain behaviors.100101After:102103def group_users_by_id(user_id):104 """Groups users by id to a specific category (1-9).105 Warning: Certain characters might not be handled correctly.106 Please refer to the documentation for supported formats.107 Args:108 user_id (str): The user id to be grouped.109 Returns:110 int: The category number (1-9) corresponding to the user id.111 Raises:112 ValueError: If the user id is invalid or unsupported.113 """114 # ... complex logic ...115 # ... more code …116117This comment provides meaningful information about the function's behavior and explains unusual behavior and potential pitfalls.1181194. Write Short Functions That Only Do One Thing120121Follow the single responsibility principle (SRP), which means that a function should have one purpose and perform it effectively. Functions are more understandable, readable, and maintainable if they only have one job. It also makes testing them very easy. If a function becomes too long or complex, consider breaking it into smaller, more manageable functions.122123Example:124125Before:126127def process_data(data):128 # ... validate users...129 # ... calculate values ...130 # ... format output …131132This function performs three tasks: validating users, calculating values, and formatting output. If any of these steps fail, the entire function fails, making debugging a complex issue. If we also need to change the logic of one of the tasks, we risk introducing unintended side effects in another task.133134Instead, try to assign each task a function that does just one thing.135136After:137138def validate_user(data):139 # ... data validation logic ...140141def calculate_values(data):142 # ... calculation logic based on validated data ...143144def format_output(data):145 # ... format results for display …146147The improved code separates the tasks into distinct functions. This results in more readable, maintainable, and testable code. Also, If a change needs to be made, it will be easier to identify and modify the specific function responsible for the desired functionality.1481495. Follow the DRY (Don't Repeat Yourself) Principle and Avoid Duplicating Code or Logic150151Avoid writing the same code more than once. Instead, reuse your code using functions, classes, modules, libraries, or other abstractions. This makes your code more efficient, consistent, and maintainable. It also reduces the risk of errors and bugs as you only need to modify your code in one place if you need to change or update it.152153Example:154155Before:156157def calculate_book_price(quantity, price):158 return quantity * price159160def calculate_laptop_price(quantity, price):161 return quantity * price162163In the above example, both functions calculate the total price using the same formula. This violates the DRY principle.164165We can fix this by defining a single calculate_product_price function that we use for books and laptops. This reduces code duplication and helps improve the maintenance of the codebase.166167After:168169def calculate_product_price(product_quantity, product_price):170 return product_quantity * product_price1711726. Follow Established Code-Writing Standards173174Know your programming language's conventions in terms of spacing, comments, and naming. Most programming languages have community-accepted coding standards and style guides, for example, PEP 8 for Python and Google JavaScript Style Guide for JavaScript.175176Here are some specific examples:177178Java:179Use camelCase for variable, function, and class names.180Indent code with four spaces.181Put opening braces on the same line.182183Python:184Use snake_case for variable, function, and class names.185Use spaces over tabs for indentation.186Put opening braces on the same line as the function or class declaration.187188JavaScript:189Use camelCase for variable and function names.190Use snake_case for object properties.191Indent code with two spaces.192Put opening braces on the same line as the function or class declaration.193194Also, consider extending some of these standards by creating internal coding rules for your organization. This can contain information on creating and naming folders or describing function names within your organization.1951967. Encapsulate Nested Conditionals into Functions197198One way to improve the readability and clarity of functions is to encapsulate nested if/else statements into other functions. Encapsulating such logic into a function with a descriptive name clarifies its purpose and simplifies code comprehension. In some cases, it also makes it easier to reuse, modify, and test the logic without affecting the rest of the function.199200In the code sample below, the discount logic is nested within the calculate_product_discount function, making it difficult to understand at a glance.201202Example:203204Before:205206def calculate_product_discount(product_price):207 discount_amount = 0208 if product_price > 100:209 discount_amount = product_price * 0.1210 elif price > 50:211 discount_amount = product_price * 0.05212 else:213 discount_amount = 0214 final_product_price = product_price - discount_amount215 return final_product_price216217We can clean this code up by separating the nested if/else condition that calculates discount logic into another function called get_discount_rate and then calling the get_discount_rate in the calculate_product_discount function. This makes it easier to read at a glance. The get_discount_rate is now isolated and can be reused by other functions in the codebase. It’s also easier to change, test, and debug it without affecting the calculate_discount function.218219After:220221def calculate_discount(product_price):222 discount_rate = get_discount_rate(product_price)223 discount_amount = product_price * discount_rate224 final_product_price = product_price - discount_amount225 return final_product_price226227def get_discount_rate(product_price):228 if product_price > 100:229 return 0.1230 elif product_price > 50:231 return 0.05232 else:233 return 02342358. Refactor Continuously236237Regularly review and refactor your code to improve its structure, readability, and maintainability. Consider the readability of your code for the next person who will work on it, and always leave the codebase cleaner than you found it.2382399. Use Version Control240241Version control systems meticulously track every change made to your codebase, enabling you to understand the evolution of your code and revert to previous versions if needed. This creates a safety net for code refactoring and prevents accidental deletions or overwrites. Use version control systems like GitHub, GitLab, and Bitbucket to track changes to your codebase and collaborate effectively with others.242243
Full transparency — inspect the skill content before installing.