How to Turn Ugly Code into Beautiful Code

Time: Column:Python views:223

Below are two examples of code refactoring in different scenarios, showing how to transform complex or unclear code into a more concise, readable, and maintainable form.

Example 1: Refactoring a Function with Complex Conditions

Ugly Code Example
Here’s a function that determines the movie ticket price based on age and membership status:

def calculate_ticket_price(age, is_member):
    if age < 18:
        if is_member:
            return 6
        else:
            return 8
    else:
        if is_member:
            return 10
        else:
            return 12

While this code works, the multiple nested conditional statements make it difficult to read and maintain.

Improved Code
We can simplify this function using early returns and conditional expressions:

def calculate_ticket_price(age, is_member):
    if age < 18:
        return 6 if is_member else 8
    return 10 if is_member else 12

In this refactored version:

  • Conditional expressions reduce nesting.

  • Early returns clarify the logic for different age groups.

The code is now cleaner and easier to understand.


Example 2: Simplifying Mixed Loops and Conditional Logic

Ugly Code Example
Here’s a function that checks if all elements in a list satisfy a specific condition:

def all_elements_positive(lst):
    result = True
    for elem in lst:
        if elem <= 0:
            result = False
            break
    return result

This code uses a loop and an internal conditional statement to set a flag variable. While it’s logically correct, it’s not concise.

Improved Code
We can use Python’s built-in all() function to simplify this:

def all_elements_positive(lst):
    return all(elem > 0 for elem in lst)

The refactored version takes advantage of the all() function, which directly checks if all elements in an iterable satisfy a condition. This approach:

  • Reduces verbosity

  • Improves readability and efficiency


Summary

These two examples demonstrate how to leverage Python features such as conditional expressions and built-in functions to simplify code. Refactoring in this way not only improves code readability and maintainability but also aligns it with Pythonic programming practices. In real-world development, mastering these techniques can help developers write more efficient and understandable code.