Prompt Details
Model
(claude-4-sonnet)
Token size
99
Example input
[codebase_name]: MyEcommerceApp
[programming_language]: Python 3.9
[error_context]: IndexError: list index out of range in OrderProcessor
[design_principles]: SOLID and DRY architecture
Example output
Here is your **diagnostic blueprint** to automate debugging and refactoring for `MyEcommerceApp`, specifically targeting the `IndexError: list index out of range` in `OrderProcessor`, while staying aligned with **Python 3.9**, **SOLID**, and **DRY** principles.
---
## β
Part 1: **Root Cause Analysis β `IndexError: list index out of range` in `OrderProcessor`**
### π Common Causes:
1. **Empty or insufficient list access**:
```python
order_items[0] # Error if list is empty
```
2. **Off-by-one errors in loops or indexing**.
3. **Assumptions about external data (e.g., API or DB) not being validated**.
### π§ Diagnostic Automation Strategy:
Use a `diagnostic wrapper` to log context and inspect list bounds before access.
```python
def safe_get(lst, idx, default=None):
if 0 <= idx < len(lst):
return lst[idx]
logger.warning(f"Index {idx} out of range for list of length {len(lst)}.")
return default
```
Inject this wrapper or refactor any direct access to enforce safe indexing.
---
## β
Part 2: **Corrective Patterns (SOLID + DRY Alignment)**
| Issue | Violation | Refactoring Pattern |
| ------------------------ | --------------------- | -------------------------------------------- |
| Unsafe list access | Single Responsibility | Encapsulate list access logic |
| Inline index assumptions | DRY | Reuse validation utilities |
| Mixed concerns | Interface Segregation | Separate order validation from processing |
| Incohesive data handling | Liskov Substitution | Use abstract base classes for list providers |
### β
Example Refactor
**Before**:
```python
def process_order(order):
first_item = order['items'][0] # risky
```
**After (SOLID + DRY-aligned)**:
```python
class OrderValidator:
@staticmethod
def has_items(order) -> bool:
return bool(order.get("items"))
class OrderProcessor:
def __init__(self, validator: OrderValidator):
self.validator = validator
def process(self, order):
if not self.validator.has_items(order):
raise ValueError("Order contains no items")
first_item = order["items"][0]
# continue processing...
```
---
## β
Part 3: **Step-by-Step Refactoring Roadmap**
### π Step 1: Automated List Safety Validation
* Replace `[index]` with `safe_get` or conditional logic.
* Introduce centralized data access helpers.
### π Step 2: Decompose `OrderProcessor`
* Break down `OrderProcessor` into:
* `OrderValidator`
* `OrderCalculator`
* `OrderFinalizer`
* Apply **Single Responsibility** and **Dependency Inversion**.
### π― Step 3: Unit Test Reinforcement
* Use `pytest` and `pytest-mock` to:
* Cover boundary tests (empty lists, large indexes).
* Add property-based tests with `hypothesis`.
### β‘ Step 4: Performance Improvements
* Profile `OrderProcessor` with `cProfile`.
* Use generator expressions for large lists.
* Consider `dataclasses` for data-heavy objects to improve readability and performance.
```python
from dataclasses import dataclass
@dataclass
class OrderItem:
product_id: str
quantity: int
```
---
## β
Part 4: CI/CD & Tooling Integration
### π οΈ CI/CD Pipelines (GitHub Actions or GitLab CI)
```yaml
# .github/workflows/ci.yml
name: CI Pipeline
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: 3.9
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest flake8 black mypy
- name: Lint
run: |
flake8 .
black --check .
mypy .
- name: Run Tests
run: pytest --cov=my_ecommerce_app
```
---
### π§° Recommended Tools:
| Tool | Purpose |
| -------------------------------- | ---------------------------- |
| **Black** | Code formatting |
| **Flake8** | Linting |
| **mypy** | Type checking |
| **pytest + coverage.py** | Unit testing |
| **hypothesis** | Property-based testing |
| **Bandit** | Security checks |
| **SonarQube** or **CodeClimate** | Code quality monitoring |
| **Dependabot** | Dependency update automation |
---
## β
Summary Blueprint
| Objective | Action |
| ------------------------- | ----------------------------------------------- |
| **Prevent IndexError** | Abstract and validate list accesses |
| **Improve Readability** | Decompose processor, apply SRP and DRY |
| **Boost Performance** | Profile, optimize data access |
| **Enhance Test Coverage** | Add boundary and hypothesis-based tests |
| **Streamline Delivery** | Integrate CI/CD with linting, testing, coverage |
| **Future-Proofing** | Adopt static typing, enforce SOLID structure |
---
Would you like a code generator to automate the decomposition of `OrderProcessor` into SOLID-compliant services with test scaffolding included?
By purchasing this prompt, you agree to our terms of service
CLAUDE-4-SONNET
Experience a seamless way to pinpoint, debug, and refactor my codebase in minutes.
Leverage an expert-designed blueprint that adapts to any language, framework, or architectural style.
Follow a clear, step-by-step roadmap that enhances performance, readability, and test coverage.
Integrate effortlessly with CI/CD pipelines and modern tooling to accelerate delivery and reduce technical debt.
...more
Added over 1 month ago
