Refactoring is not simply about making code shorter, prettier, or faster. It is the process of improving the internal structure of software without changing its external behavior.
As software evolves, its codebase naturally becomes more complex. New features are added, requirements change, and temporary solutions sometimes become permanent. Over time, duplicated logic, overly complicated functions, classes with too many responsibilities, and tightly coupled components can make the codebase increasingly difficult to understand and maintain.
Refactoring helps address these problems. It allows developers to improve the design of existing code, making it easier to read, modify, extend, and maintain.
There are many refactoring techniques and design principles that can help achieve this goal. Here are some that I find particularly useful in everyday software development.
Extract Method
A function should ideally perform one clear task. When a function contains too many steps or handles several different responsibilities, it becomes difficult to understand and maintain.
Extract Method is a technique for moving a group of related statements into a separate function with a meaningful name.
For example, the checkout function below calculates the total, applies a discount, and prints the result:
# Before: one function does three things
def checkout(cart):
total = 0
for item in cart:
total += item["price"] * item["qty"]
if total > 1_000_000:
total = total * 0.9
print(f"Total: {total}")
return total
# After: each step has a name
def checkout(cart):
total = apply_discount(subtotal(cart))
print(f"Total: {total}")
return total
def subtotal(cart):
return sum(item["price"] * item["qty"] for item in cart)
def apply_discount(total):
return total * 0.9 if total > 1_000_000 else total
After the extraction, reading checkout shows the two steps right away: calculate the subtotal, then apply the discount. You only open apply_discount when you need to know how the discount works.
This makes the original function easier to read because its high-level flow becomes more visible. It also allows the extracted logic to be reused or tested independently when appropriate.
The goal is not to create as many small functions as possible. It is to give each function a clear purpose and make the code easier to understand.
Remove Duplicate Code
Duplicate code is one of the common sources of maintenance problems.
When the same logic exists in multiple places, a change may need to be applied to every copy. If one instance is updated while another is forgotten, the application can behave inconsistently.
Identifying duplicated logic and extracting it into a shared function or component can reduce this risk.
For example, the VAT calculation is written twice, once for invoices and once for quotes:
# Before: the same VAT rule is written in two places
def invoice_total(amount):
return amount + amount * 0.1
def quote_total(amount):
return amount + amount * 0.1
# After: the rule lives in one place
VAT_RATE = 0.1
def with_vat(amount):
return amount + amount * VAT_RATE
def invoice_total(amount):
return with_vat(amount)
def quote_total(amount):
return with_vat(amount)
When VAT changes from 10% to 8%, only VAT_RATE needs to change. In the first version, updating invoice_total and forgetting quote_total would make invoices and quotes disagree.
However, not every similar-looking piece of code should be merged. Two pieces of code may look similar today but represent different business rules that are likely to evolve independently.
The important thing is to eliminate meaningful duplication without introducing unnecessary abstractions.
Keep Classes Focused
A class becomes difficult to maintain when it takes on too many unrelated responsibilities.
For example, a single class might handle database access, business rules, input validation, and notification delivery. Changes to one area can then affect other areas, making the class harder to understand and test.
Keeping classes focused means organizing related behavior together while separating responsibilities that do not naturally belong together.
For example, an OrderService that calculates prices, saves orders, and sends emails:
# Before: one class handles pricing, storage, and email
class OrderService:
def total(self, order): ...
def save(self, order): ...
def send_confirmation_email(self, order): ...
# After: each class has one reason to change
class PriceCalculator:
def total(self, order): ...
class OrderRepository:
def save(self, order): ...
class OrderNotifier:
def send_confirmation(self, order): ...
Switching email providers now touches only OrderNotifier. Pricing and storage stay untouched.
This idea is closely related to the Single Responsibility Principle (SRP).
A class does not necessarily need to contain only one method or perform only one tiny operation. Rather, it should have a clear purpose and a coherent set of responsibilities.
Move Behavior to the Right Object
Sometimes, a class contains data while another class is responsible for performing operations on that data.
This can lead to unnecessary dependencies and make the code harder to maintain. The logic may be better placed inside the object that owns or understands the relevant data.
For example, instead of passing an object to an external function that calculates its total price, the calculation might belong inside the object itself.
# Before: Order only holds data, the rule lives outside
class Order:
def __init__(self, items):
self.items = items
def order_total(order):
return sum(price * qty for price, qty in order.items)
# After: Order computes its own total
class Order:
def __init__(self, items):
self.items = items
def total(self):
return sum(price * qty for price, qty in self.items)
When the total rule changes, for example to add a shipping fee, only Order.total() changes. There is no need to hunt for functions like order_total scattered across the codebase.
Moving behavior to the right object helps keep data and the operations related to that data together.
However, this does not mean every operation should be placed inside a data object. The responsibility should be assigned based on the domain and the role of each component.
Encapsulation
Encapsulation is about controlling how an object’s internal state and implementation details are accessed.
Instead of allowing other parts of the application to modify internal data directly, an object exposes a clear interface through which other components can interact with it.
This gives the object control over its own state and helps protect its invariants.
For example, an account object should not allow arbitrary code to change its balance to any value. It can expose methods such as deposit() and withdraw() to ensure that changes follow the appropriate business rules.
# Before: any code can set the balance to anything
account.balance = -500
# After: changes go through methods that check the rules
class Account:
def __init__(self):
self._balance = 0
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("insufficient balance")
self._balance -= amount
In the second version, _balance is internal to the object. The way to change it is through a method such as withdraw(), which checks the rules first.
Good encapsulation reduces the number of places that need to understand an object’s internal implementation.
As a result, internal changes can be made with less impact on the rest of the system.
Introduce Parameter Object
Functions sometimes receive many parameters, especially when several parameters are closely related.
For example, a function that creates a shipment might accept the street, district, city, and phone number as separate arguments.
As the application grows, more related parameters may be added, making the function signature increasingly difficult to read and maintain.
Introduce Parameter Object is a refactoring technique that groups related parameters into a single object.
from dataclasses import dataclass
# Before: four parameters that always travel together
def create_shipment(order_id, street, district, city, phone): ...
# After: they become one Address object
@dataclass(frozen=True)
class Address:
street: str
district: str
city: str
phone: str
def create_shipment(order_id, address: Address): ...
Adding a new address field, such as ward, now only changes Address. The signature of create_shipment and its callers stay the same.
This makes function calls clearer and provides a meaningful structure for related data. It can also make it easier to extend the function when new related fields are introduced.
However, parameters should only be grouped when they represent a meaningful concept. Creating an object for unrelated values simply to reduce the number of parameters may make the design more complicated.
Simplify Conditional Logic
Complex conditional logic can make code difficult to follow.
Nested if statements, repeated conditions, and complicated boolean expressions often hide the actual business rules.
There are several ways to simplify this logic:
- Extract complex conditions into well-named functions.
- Combine conditions when they represent the same decision.
- Remove unnecessary branches.
- Use clearer names for boolean variables.
- Consider polymorphism when behavior varies significantly between different types.
The objective is to make the intention of the code obvious.
For example, here is a long boolean expression, and the same check with a name:
# Before: the reader has to decode the condition
if not (user.age < 18 or user.banned) and user.verified:
place_order(cart)
# After: the condition has a name
def can_buy(user):
is_adult = user.age >= 18
return is_adult and not user.banned and user.verified
if can_buy(user):
place_order(cart)
In the first version, the reader has to untangle not (... or ...) in their head. In the second, if can_buy(user) reads as a sentence, and the details live in can_buy.
A developer reading the code should be able to understand why a particular branch is executed without having to mentally evaluate several layers of conditions.
Use Guard Clauses
Deeply nested conditional statements can make the main execution path difficult to understand.
Guard Clauses help address this by checking exceptional or invalid conditions at the beginning of a function and returning early when necessary.
For example, instead of wrapping the entire function body inside an if statement that checks whether the input is valid, the function can immediately return when the input is invalid.
# Before: the main logic is buried three levels deep
def ship(order):
if order is not None:
if order.paid:
if order.items:
return "shipping"
else:
return "empty order"
else:
return "not paid"
else:
return "no order"
# After: handle the special cases first
def ship(order):
if order is None:
return "no order"
if not order.paid:
return "not paid"
if not order.items:
return "empty order"
return "shipping"
The second version has no else and no nesting. The three special cases are handled at the top, and the last line is the main path.
This reduces nesting and makes the normal execution path easier to follow.
Guard Clauses are particularly useful for handling validation errors, missing data, unauthorized access, and other conditions that should prevent further execution.
The result is flatter code with a clearer flow.
Reduce Coupling
Coupling describes how strongly one component depends on another.
When components are tightly coupled, changing one part of the system can require changes in several other places. This makes the application harder to maintain, test, and extend.
Reducing coupling means designing components so that they depend on clear interfaces rather than unnecessary implementation details.
For example, a business service should not need to know the internal details of a specific database implementation. It can depend on a repository interface instead.
# Before: the service creates its own database
class OrderService:
def __init__(self):
self.db = PostgresDatabase()
# After: the service receives a repository
class OrderService:
def __init__(self, repo):
self.repo = repo
service = OrderService(FakeRepository()) # easy to test
In the second version, OrderService does not know whether orders go to Postgres, MongoDB, or an in-memory list. In tests, passing a fake repository is enough, with no real database to set up.
This makes it easier to replace implementations, test components independently, and evolve the system over time.
The goal is not to eliminate all dependencies. Dependencies are necessary in software. The goal is to make them explicit, controlled, and easier to manage.
Replace Primitive with Object
Primitive types such as strings, numbers, and booleans are useful for representing simple values.
However, using them everywhere can make domain concepts difficult to understand and protect.
For example, an email address represented as a plain string can contain any value, even one that is not a valid email address. A monetary amount represented as a number may also lack important information, such as its currency.
Replace Primitive with Object is a refactoring technique that introduces a dedicated type or object to represent a meaningful concept.
Instead of passing around an arbitrary string, the application can use an EmailAddress object that validates its value. Similarly, a Money object can encapsulate an amount and its currency.
# Before: an email is just a string, so any value is accepted
def register(email: str): ...
register("not-an-email") # no error
# After: the rule lives in one type
class EmailAddress:
def __init__(self, value: str):
if "@" not in value:
raise ValueError(f"invalid email: {value}")
self.value = value.lower()
def register(email: EmailAddress): ...
An invalid EmailAddress can no longer be created. Functions that receive one do not need to validate it again, and the email rule lives in a single place.
This makes the domain model more expressive and allows validation and behavior to live closer to the data they belong to.
It is not necessary to create custom objects for every primitive value. This technique is most useful when a value has its own rules, constraints, or behavior.
Remove Dead Code
Dead code is code that is no longer executed, referenced, or needed by the application.
It can include unused functions, outdated classes, unreachable branches, obsolete configuration, and code left behind after a feature has been removed.
Keeping dead code around creates unnecessary complexity. Developers may spend time investigating code that has no effect on the application, and outdated implementations can make the codebase harder to understand.
Removing unused code helps keep the codebase smaller and easier to navigate.
Before deleting code, it is important to verify that it is genuinely unused. Some code may only be executed through dynamic imports, reflection, external integrations, or scheduled jobs.
Separate Query from Modifier
A function that reads data and a function that changes data have different responsibilities.
When a single function does both, it can be difficult to understand its side effects. Calling a function that appears to retrieve information might unexpectedly modify the application’s state.
Separating queries from modifiers makes behavior more predictable.
A query should return information without changing the observable state of the system. A modifier should perform an operation that changes state.
For example, getAccountBalance() should only return the current balance, while withdraw() should perform the withdrawal and update the account.
Here is a version where reading the balance quietly charges a monthly fee:
# Before: reading the balance also charges a fee
def get_balance(account):
account["balance"] -= 1_000 # monthly fee, hidden here
return account["balance"]
# After: one function reads, another one changes
def get_balance(account):
return account["balance"]
def charge_monthly_fee(account):
account["balance"] -= 1_000
In the first version, calling get_balance() twice charges the fee twice, even though the name only promises a read. After the split, get_balance() is safe to call any number of times, and the fee lives in a function whose name says what it does.
This separation makes code easier to reason about, test, and use safely.
It also helps developers understand the consequences of calling a function simply by looking at its name and interface.
Refactor in Small Steps
Refactoring does not need to happen through large-scale rewrites.
In fact, changing too much code at once can introduce unnecessary risks. When a large refactoring causes a bug, identifying the source of the problem can also become difficult.
A safer approach is to make small, incremental changes.
For example:
- Identify a specific problem in the existing code.
- Make one focused structural improvement.
- Run relevant tests to verify that behavior remains unchanged.
- Review the result before moving to the next improvement.
Automated tests are particularly important because they provide confidence that refactoring has not introduced regressions.
Small steps also make code reviews easier. Reviewers can understand the intention of each change without having to analyze a large collection of unrelated modifications.
Refactoring should be an ongoing part of software development, not something that only happens when the codebase becomes difficult to maintain.
Conclusion
Refactoring is not about following a set of rules blindly or applying every technique whenever possible.
Each technique solves a particular problem, and not every situation requires the same solution. A good refactoring decision depends on the current design, business requirements, and expected future changes.
The main objective is to make software easier to understand, change, extend, and maintain.
In my opinion, good code is not necessarily the code with the fewest lines or the most abstractions. It is code that communicates its intent clearly, keeps responsibilities well organized, and allows developers to make changes without introducing unnecessary complexity.
Ultimately, refactoring is a continuous practice. Small improvements made consistently can have a significant impact on the long-term quality of a software project.