Prompt Details
Model
(gemini-3.0-pro)
Token size
377
Example input
[VARIABLE 1: PASTE_LEGACY_CODE_HERE]: def calculate_order_total(items, shipping_cost, discount_code): total = sum(item('price') * item('quantity') for item in items) if discount_code == "SAVE10": total *= 0.9 total += shipping_cost return total
[VARIABLE 2: CODE_LANGUAGE]: Python 3
[VARIABLE 3: PRINCIPLES_TO_APPLY]: Separation of Concerns, Single Responsibility Principle
[VARIABLE 4: MODULE_GOAL]: Decouple discount calculation and shipping logic from core total calculation.
[VARIABLE 5: RESPONSE_TONE]: Professional and detailed with clear explanations.
Example output
This analysis focuses on refactoring the `calculate_order_total` function to transition from a monolithic script to a modular, maintainable design using **Single Responsibility Principle (SRP)** and **Separation of Concerns (SoC)**.
---
## Refactoring Plan
The original code suffers from "Fat Function" syndrome—it knows too much about the internals of discounts and shipping. Here is the plan to decouple these concerns:
* **Extract Subtotal Logic:** Create a dedicated method to handle the raw calculation of item prices. This isolates the data structure of the "items" list.
* **Implement Discount Strategy:** Instead of hardcoding "SAVE10", we will introduce a mechanism to handle various discount types. This prevents the core calculator from needing a code change every time a new marketing promotion is created.
* **Decouple Shipping:** Shipping is a distinct business domain. We will treat it as a separate calculation step that can be injected or passed, allowing for future logic like "free shipping over $100."
* **Dependency Injection:** We will pass the discount and shipping values into the calculation process rather than having the function "reach out" or hardcode those rules.
---
## Refactored Code
By breaking the logic into smaller, focused components, the code becomes more readable and significantly easier to test.
```python
from typing import List, Dict
class DiscountCalculator:
"""Handles the application of various discount codes."""
@staticmethod
def apply_discount(subtotal: float, discount_code: str) -> float:
# In a real scenario, this might look up a database or config
discounts = {
"SAVE10": 0.10,
"SAVE20": 0.20
}
multiplier = 1 - discounts.get(discount_code, 0.0)
return subtotal * multiplier
class OrderCalculator:
"""Core logic for orchestrating order totals."""
@staticmethod
def calculate_subtotal(items: List[Dict]) -> float:
return sum(item['price'] * item['quantity'] for item in items)
def calculate_total(self, items: List[Dict], shipping_cost: float, discount_code: str = None) -> float:
# 1. Calculate base subtotal
subtotal = self.calculate_subtotal(items)
# 2. Apply discount logic (Separation of Concerns)
discounted_total = DiscountCalculator.apply_discount(subtotal, discount_code)
# 3. Add shipping (Decoupled logic)
final_total = discounted_total + shipping_cost
return round(final_total, 2)
```
---
## Unit Test Suite
To ensure the refactoring remains stable, we use the `unittest` framework to validate individual responsibilities.
```python
import unittest
class TestOrderCalculator(unittest.TestCase):
def setUp(self):
self.calculator = OrderCalculator()
self.sample_items = [
{'price': 10.0, 'quantity': 2}, # 20.0
{'price': 5.0, 'quantity': 2} # 10.0
]
def test_calculate_subtotal(self):
"""Test that subtotal is calculated correctly regardless of discounts."""
subtotal = self.calculator.calculate_subtotal(self.sample_items)
self.assertEqual(subtotal, 30.0)
def test_apply_discount_valid(self):
"""Test the SAVE10 discount logic specifically."""
subtotal = 100.0
result = DiscountCalculator.apply_discount(subtotal, "SAVE10")
self.assertEqual(result, 90.0)
def test_apply_discount_invalid(self):
"""Test that unknown codes do not affect the price."""
subtotal = 100.0
result = DiscountCalculator.apply_discount(subtotal, "INVALID")
self.assertEqual(result, 100.0)
def test_full_order_calculation(self):
"""Test the full orchestration of subtotal, discount, and shipping."""
# (30.0 subtotal - 10% discount) + 5.0 shipping = 32.0
total = self.calculator.calculate_total(self.sample_items, 5.0, "SAVE10")
self.assertEqual(total, 32.0)
if __name__ == '__main__':
unittest.main()
```
### Why this is better:
1. **SRP:** If the way you calculate a subtotal changes (e.g., adding tax per item), you only touch `calculate_subtotal`.
2. **Extensibility:** Adding a "SAVE50" code no longer requires modifying the `OrderCalculator` class; you only update the `DiscountCalculator`.
3. **Testability:** You can now test the discount logic without needing to create a list of items, and vice versa.
Would you like me to expand the `DiscountCalculator` to handle percentage vs. flat-rate discounts using the Strategy Design Pattern?
By purchasing this prompt, you agree to our terms of service
GEMINI-3.0-PRO
Stuck with legacy code? This AI acts as your expert Software Architect and Mentor, guiding junior engineers through migrating monolithic systems to modern microservices architectures. By applying SOLID principles and best practices, the template refactors old code snippets (Python, Java, C#, etc.) and automatically generates comprehensive unit tests. Transform boring migration tasks into educational, high-quality engineering work. A must-have tool for any engineer dealing with technical debt!
...more
Added over 1 month ago
