{"id":63,"date":"2025-01-14T22:51:19","date_gmt":"2025-01-14T22:51:19","guid":{"rendered":"https:\/\/blogs.oregonstate.edu\/hridayblog\/?p=63"},"modified":"2025-01-14T23:41:16","modified_gmt":"2025-01-14T23:41:16","slug":"clean-code-and-code-smells","status":"publish","type":"post","link":"https:\/\/blogs.oregonstate.edu\/hridayblog\/2025\/01\/14\/clean-code-and-code-smells\/","title":{"rendered":"Clean Code and Code Smells"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\" style=\"font-size:25px\">Introduction<\/h3>\n\n\n\n<p>Writing clean code is not just a skill; it\u2019s a responsibility every programmer should embrace. Clean code makes a codebase easier to read, maintain, and debug, which saves time and prevents headaches. On the other hand, code smells are warning signs that indicate deeper issues in the code, leading to technical debt and maintenance nightmares. After reading <strong>\u201cWhat Is Clean Code?\u201d<\/strong> by Codacy and <strong>\u201cCommon Code Smells\u201d<\/strong> by 8th Light, I\u2019ve identified one practice I want to adopt more often and one practice I want to avoid at all costs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" style=\"font-size:25px\">What I Want to Start Doing: Writing Short, Single-Purpose Functions<\/h3>\n\n\n\n<p>One of the principles of clean code that stood out to me was <strong>writing short functions that do only one thing<\/strong>, also known as the <strong>Single Responsibility Principle (SRP)<\/strong>. Breaking down a function into smaller, purpose-driven chunks makes code more readable, easier to debug, and reusable in different parts of a project.<\/p>\n\n\n\n<p>Here\u2019s an example of bad practice, where a single function is overloaded with multiple responsibilities:<\/p>\n\n\n\n<pre class=\"wp-block-code has-luminous-vivid-orange-color has-text-color has-background has-link-color wp-elements-071c521b2c9f49fd736e3bd95ae40586\" style=\"background-color:#292929\"><code>\n def process_order(order):\n     # Validate order\n     if not order.is_valid():\n         return \"Invalid order\"\n     # Calculate total price\n     total_price = sum(item.price for item in order.items)\n     if order.has_discount:\n         total_price *= 0.9  # Apply discount\n     # Save to database\n     database.save_order(order, total_price)\n     return \"Order processed\"\n\n<\/code><\/pre>\n\n\n\n<p>This function is doing too much: validation, calculation, and saving data. It\u2019s a classic code smell, known as Long Methods, as described in the 8th Light article.<\/p>\n\n\n\n<p>Here\u2019s a cleaner, refactored version:<\/p>\n\n\n\n<pre class=\"wp-block-code has-luminous-vivid-orange-color has-text-color has-background has-link-color wp-elements-86b7b187fac3d951e939b24c1ccf32f6\" style=\"background-color:#292929\"><code>\n def validate_order(order):\n     if not order.is_valid():\n         return False\n     return True\n\n def calculate_total_price(order):\n     total = sum(item.price for item in order.items)\n     if order.has_discount:\n         total *= 0.9\n     return total\n\n def save_order(order, total_price):\n     database.save_order(order, total_price)\n \n def process_order(order):\n     if not validate_order(order):\n         return \"Invalid order\"\n     total_price = calculate_total_price(order)\n     save_order(order, total_price)\n     return \"Order processed\"\n\n<\/code><\/pre>\n\n\n\n<p>Each function now has a single purpose, making it easier to read, debug, and test independently. I aim to implement this principle consistently in my future projects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" style=\"font-size:25px\">What I Want to Avoid: Hard-Coded Values<\/h3>\n\n\n\n<p>From the Codacy article, I learned about the problems caused by <strong>hard-coded values<\/strong> (magic numbers). They reduce readability, make code harder to maintain, and increase the risk of errors when requirements change. For example, imagine encountering this piece of code in a large codebase:<\/p>\n\n\n\n<pre class=\"wp-block-code has-luminous-vivid-orange-color has-text-color has-background has-link-color wp-elements-9079609e3ac75c68c61b0e0146525b6c\" style=\"background-color:#292929\"><code>\n if user.age &gt; 18:\n     discount = order_total * 0.1  # 10% discount\n else:\n     discount = 0\n\n<\/code><\/pre>\n\n\n\n<p>While the logic works, it\u2019s unclear why the age is set to 18 or why the discount is 10%. This ambiguity can confuse other developers (or even future me).<\/p>\n\n\n\n<p>A better approach is to use named constants:<\/p>\n\n\n\n<pre class=\"wp-block-code has-luminous-vivid-orange-color has-text-color has-background has-link-color wp-elements-fa1c30431d688fe001b684a5448fe5f3\" style=\"background-color:#292929\"><code> \n MINIMUM_AGE_FOR_DISCOUNT = 18\n DISCOUNT_RATE = 0.1\n \n if user.age &gt; MINIMUM_AGE_FOR_DISCOUNT:\n     discount = order_total * DISCOUNT_RATE\n else:\n     discount = 0\n\n<\/code><\/pre>\n\n\n\n<p>Now, the code is self-documenting, and any changes (e.g., raising the age threshold to 21) can be made in one place.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" style=\"font-size:25px\">The Importance of Clean Code<\/h3>\n\n\n\n<p>Clean code isn\u2019t just about aesthetics; it\u2019s about functionality and teamwork. Clean code ensures that:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>New team members can onboard quickly.<\/strong> They don\u2019t need hours to decipher poorly written code.<\/li>\n\n\n\n<li><strong>Debugging becomes easier.<\/strong> Clear code makes it simpler to pinpoint the source of issues.<\/li>\n\n\n\n<li><strong>Future changes are painless.<\/strong> Maintainability is a critical aspect of software longevity.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" style=\"font-size:25px\">Recognizing and Addressing Code Smells<\/h3>\n\n\n\n<p>Code smells are subtle signs of trouble in the codebase. While they don\u2019t always break functionality, they make code harder to maintain and extend. Some common smells I\u2019ll actively look out for include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Duplicate Code:<\/strong> It leads to inconsistencies when updates are made to one part of the code but not the duplicate.<\/li>\n\n\n\n<li><strong>Data Clumps:<\/strong> Repeated groups of parameters are better encapsulated in a class or data structure.<\/li>\n\n\n\n<li><strong>Refused Bequest:<\/strong> If a subclass doesn\u2019t use methods from its parent class, it\u2019s likely a sign that inheritance is being misused.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" style=\"font-size:25px\">Conclusion<\/h3>\n\n\n\n<p>By adopting clean code practices, such as writing short, single-purpose functions, and avoiding pitfalls like hard-coded values, I can improve the quality of my code and ensure it remains maintainable and extensible. Recognizing and addressing code smells early will prevent technical debt and promote a collaborative, efficient development process.<\/p>\n\n\n\n<p>Let\u2019s strive to leave every codebase we touch better than we found it!<\/p>\n\n\n\n<p><strong>References:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"https:\/\/blog.codacy.com\/what-is-clean-code\">What Is Clean Code? A Guide to Principles and Best Practices<\/a> &#8211; Codacy<\/li>\n\n\n\n<li><a href=\"https:\/\/8thlight.com\/insights\/common-code-smells\">Common Code Smells<\/a> &#8211; 8th Light<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>Lessons Learned and Practices to Adopt<\/p>\n","protected":false},"author":14447,"featured_media":67,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[],"class_list":["post-63","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cs-462"],"_links":{"self":[{"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/posts\/63","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/users\/14447"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/comments?post=63"}],"version-history":[{"count":5,"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/posts\/63\/revisions"}],"predecessor-version":[{"id":71,"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/posts\/63\/revisions\/71"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/media\/67"}],"wp:attachment":[{"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/media?parent=63"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/categories?post=63"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.oregonstate.edu\/hridayblog\/wp-json\/wp\/v2\/tags?post=63"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}