SOLID principles in Software Engineering - Time & Space Complexity
We want to understand how the SOLID principles affect the time it takes for software to run.
Specifically, how following these principles changes the work done as programs grow.
Analyze the time complexity of a class that violates the Single Responsibility Principle.
class OrderProcessor:
def __init__(self, order):
self.order = order
def calculate_total(self):
total = 0
for item in self.order.items:
total += item.price * item.quantity
return total
def save_order(self):
database.save(self.order)
This class handles order calculation and saving, mixing responsibilities.
Look at loops and repeated work in the code.
- Primary operation: Looping through all items in the order to calculate total.
- How many times: Once per item in the order.
The time to calculate the total grows as the number of items grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions and multiplications |
| 100 | 100 additions and multiplications |
| 1000 | 1000 additions and multiplications |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to calculate grows in a straight line as the order gets bigger.
[X] Wrong: "Mixing responsibilities in one class makes the program faster."
[OK] Correct: Combining tasks can make code harder to maintain and can hide costly operations, not necessarily faster.
Understanding how SOLID principles affect code structure and performance shows you can write clear and efficient programs.
"What if we split the class so each handles only one task? How would that affect the time complexity?"