Categories
Uncategorized

Code Well vs. Code Smell

Clean Code

Clean code is defined by its readability, simplicity, and how easily it can be maintained. Writing clean code ensures that codebases are understandable and modifiable by any developer at any point in time. This leads to improved collaboration, reduced errors, and more efficient development processes.

For example, let’s take a function that calculates the area of a rectangle:

def a(w, h):

    return w * h

While logically and syntactically sound, the above code is not very clear. We can easily fix this by renaming the function and its parameters to more descriptive names. See the improved function below.

def calculate_area(width, height):

    return width * height

Better right? This is a very simplified example of how we can keep our code clean and understandable but there are many others.

Smelly Code

Code smells are pieces or attributes of code that could cause issues within the codebase. Ignoring these signs can result in over complication, more bugs, and difficulties maintaining. For example, long classes or methods can make code harder to understand and modify. Let’s look at the example function below that has multiple responsibilities:

def process_data(data):

    # Validate data

    if not validate(data):

        return None

    # Transform data

    transformed = transform(data)

    # Save data

    save_to_database(transformed)

This function is handling many responsibilities: validation, transformation, and saving. Refactoring into separate functions makes your code much easier to understand and maintain.

def process_data(data):

    if not validate(data):

        return None

    transformed = transform(data)

    save_to_database(transformed)

def validate(data):

    # Validation logic

    pass

def transform(data):

    # Transformation logic

    pass

def save_to_database(data):

    # Database saving logic

    pass

Implementing the functions in this way makes the logic much easier to follow. Overall we can improve the cleanliness of our code by commenting, specific and accurate naming, keep functions as small as possible, organize your code with classes where applicable and keeping your test suites clean.

References:

Oz, Mert. “Guide on Writing Clean Code.” Medium, Trendyol Tech, 1 July 2022, medium.com/trendyol-tech/guide-on-writing-clean-code-496bb1100cde.

“Code Smell – a General Introduction and It’s Type.” GeeksforGeeks, GeeksforGeeks, 8 Sept. 2020, www.geeksforgeeks.org/code-smell-a-general-introduction-and-its-type/.