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
This is 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
Although this code works correctly, the nested conditional statements make it difficult to read and maintain.
Refactored Code
We can simplify the code by 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, we've used conditional expressions to reduce the nested conditions, and early returns to clearly separate the logic for different age groups, making the code more concise and easier to understand.
Example 2: Simplifying Mixed Loop and Condition Logic
Ugly Code Example
This is a function that checks whether 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 condition to set a flag variable. While logically correct, it's not very concise.
Refactored Code
We can simplify the function by using Python's built-in all()
function:
def all_elements_positive(lst): return all(elem > 0 for elem in lst)
In this refactored version, we leverage the all()
function, which directly checks whether all elements in an iterable meet a condition. This not only makes the code shorter but also improves readability and efficiency.
Summary
These two examples demonstrate how to simplify code by using Python's language features, such as conditional expressions and built-in functions. This refactoring improves code readability and maintainability while also aligning the code with Python's programming style. In real-world development, understanding and applying these techniques can help developers write more efficient, understandable code.