Clean code and its smells

Writing clean code is essential for creating maintainable, efficient, and scalable software. Clean code is concise, adheres to a convention, and improves the readability for other users. Code smells are indicators of potential issues in your work that may hinder future development and maintenance.

One example of clean code is meaningful names for variables, functions, and classes. Descriptive naming for these items improves readability and comprehension. This allows the code base to easily be maintained and allows others to collaborate more effectively. In the code example below you can see two different ways to perform the same mathematical calculation. When reading the two options below which option better explains that is happening?

# Poor naming
def cal(x, y):
    return x * y / 100

# Improved naming
def calculate_percentage(amount, total):
    return amount * total / 100

If you said “Improved naming”, you are correct. This example clearly shows, without comments, that this function will calculate a percentage when given the amount and total. You can improve the readability with more descriptive comments on when and where this function might be used, but this is a great first step.

The other examplem, is a great example of a code smell. Looking that the code you can tell something is not right. It’s hard to understand what and why you would need this code. This confusion you have when looking at the code is a great indicator of a code smell. I might work and make sense at the time it was made, but over time, the code become difficult to understand and unmaintainable.

This is one skill I would like to start working on this term. I have a tendency to write my code so it’s readable to me, in the moment. I will use words like “tmp” as placeholder names in my code instead of giving detailed names to improve reliability. I need to avoid write code that make sense to me and start writing code as if someone else will be reading it. This will improve productivity with my team and allow me to understand what I was doing when I look over old code.

If you want more example and a more details explanation into clean code vs smelly code look at the sources below.

Sources:
1. FreeCodeCamp. How to Write Clean Code: A Guide for Beginners. freeCodeCamp, https://www.freecodecamp.org/news/how-to-write-clean-code/. Accessed 16 Jan. 2025.
2. freeCodeCamp. Clean Coding for Beginners: Best Practices for Writing Clean Code. freeCodeCamp, https://www.freecodecamp.org/news/clean-coding-for-beginners. Accessed 16 Jan. 2025.

Leave a Reply