# CLAUDE.md - Development Philosophy

This file teaches AI coding assistants how to write code that aligns with your development philosophy. Place it at the root of your project.

**Purpose**: Capture how you THINK about software, not just coding standards. This ensures AI-generated code is maintainable and follows your patterns.

## Core Development Philosophy

### The Real Battle: Complexity

- **Complexity is the enemy** - Systems grow, context is lost, debugging becomes exponentially harder
- **Software spends 90% of life in maintenance** - You ship v1, then maintain it forever
- **ROI comes from running systems** - Value = deployed + users, not pristine unused code
- **Optimize for maintainability** - You'll be reading and modifying this in 6 months

### Development Phases (IN ORDER)

1. **Make it work** - Ship something that functions, even if messy
2. **Make it right** - Refactor for clarity and correctness (where we spend most time)
3. **Make it fast** - Optimize ONLY when profiling shows a real need

### Core Principles

- **Extensibility marks good design** - Can new features be added easily?
- **Data model first** - Get the schema right, everything else follows
- **Functions over classes** - Simple functions are easier to understand and debug
- **Service layer for logic** - Business logic in one place, not scattered
- **Explicit over implicit** - Obvious code beats clever code every time

## Patterns to Follow

### Service Layer Pattern

```python
# api_views.py - Thin HTTP wrapper
@api_view(["POST"])
def activate_user_view(request, user_id):
    # Just call the service
    success, message = activate_user(user_id, request.user)
    return api_response(success=success, message=message)

# services/user.py - Business logic lives here
def activate_user(user_id: str, admin: User) -> tuple[bool, str]:
    """All logic here - testable and reusable."""
    with transaction.atomic():
        user = User.objects.get(id=user_id)
        user.is_active = True
        user.save()
        log_activity(user, "activated", admin)
        return True, "User activated"
```

### Simple Functions Pattern

```python
# GOOD: Simple, obvious, debuggable
def process_payment(amount: float, user_id: str) -> tuple[bool, str]:
    """Process payment. Returns (success, message)."""
    if amount <= 0:
        return False, "Invalid amount"

    try:
        charge_card(user_id, amount)
        return True, "Payment processed"
    except CardError as e:
        return False, str(e)
```

## Patterns to Avoid

### Unnecessary Classes

```python
# AVOID: Class when a function would work
class EmailSender:
    def __init__(self, config):
        self.config = config

    def send(self, to, subject, body):
        # Unnecessary complexity
        pass

# PREFER: Simple function
def send_email(to: str, subject: str, body: str) -> tuple[bool, str]:
    """Just a function that sends email."""
    # Direct implementation
    pass
```

### Premature Optimization

```python
# AVOID: Optimizing before measuring
class CachedDataProcessor:
    def __init__(self):
        self.cache = {}
        self.queue = []
        # Complex caching logic for unproven need

# PREFER: Simple first, optimize when proven necessary
def process_data(data: dict) -> dict:
    """Process data simply until profiling shows issues."""
    return transform(data)
```

## Project Structure

### Where Logic Lives

```
project/
|-- services/           # ALL business logic here
|-- api/                # Thin HTTP wrappers
|-- models/             # Data models only
|-- utils/              # Shared utilities
`-- tests/              # Simple test scripts
```

- **Business Logic**: `services/` - All business rules and operations
- **API Layer**: `api/` - HTTP handling only, no business logic
- **Data Models**: `models/` - Schema and data structure
- **Utilities**: `utils/` - Shared helpers, no business logic

## Testing Philosophy

### Script-Based Testing

```python
# tests/test_user_api.py
"""
Direct API testing - no complex frameworks needed.
Tests the actual contract between backend and frontend.
"""
def test_user_activation():
    response = requests.post(
        f"{BASE_URL}/users/{user_id}/activate/",
        headers={"Authorization": f"Bearer {API_KEY}"}
    )
    assert response.status_code == 200
    data = response.json()
    assert data["success"] == True
    print("✓ User activation works")
```

## Naming Conventions

### Consistency Reduces Cognitive Load

```python
# Service functions: verb_noun
def create_user(data: dict) -> tuple[bool, str]: ...
def update_user(user_id: str, data: dict) -> tuple[bool, str]: ...
def delete_user(user_id: str) -> tuple[bool, str]: ...

# API views: noun_verb_view
def user_list_view(request): ...
def user_detail_view(request, user_id): ...
def user_activate_view(request, user_id): ...

# Boolean variables: is_ or has_ prefix
is_active = True
has_permission = False

# Constants: UPPERCASE
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
```

## Error Handling

### Simple, Explicit Errors

```python
def perform_operation(data: dict) -> tuple[bool, str]:
    """
    Standard error pattern: return (success, message).
    No exceptions for control flow.
    """
    if not data.get("required_field"):
        return False, "Missing required field"

    if not validate_data(data):
        return False, "Invalid data format"

    # Perform operation
    result = do_something(data)

    if result:
        return True, "Operation completed"
    else:
        return False, "Operation failed"
```

## Development Workflow

### Starting a New Feature

1. Write the data model first
2. Create service functions with clear inputs/outputs
3. Write simple test script to verify it works
4. Add thin API wrapper
5. Test the full flow with curl or script

### Code Review Checklist

- [ ] Is this boring code? (simple and obvious)
- [ ] Is the happy path clear?
- [ ] Can this be extended without breaking existing code?
- [ ] Could this be easily deleted and rewritten?
- [ ] Are errors handled explicitly?
- [ ] Is the business logic in the service layer?
- [ ] Are functions small and focused?

## Common Pitfalls

1. **Don't use classes when functions work** - Keep it simple
2. **Don't put logic in views/controllers** - Use service layer
3. **Don't optimize without measuring** - Profile first
4. **Don't make it clever** - Make it obvious
5. **Don't skip the data model** - It's the foundation
6. **Don't write large functions** - Break them down
7. **Don't use exceptions for control flow** - Use return values

## The Golden Rule

> **The best code is boring code - simple, obvious, and easy to delete when requirements change.**

Every line of code should optimize for clarity over cleverness. Boring code is predictable, debuggable, and replaceable.

---

## How to Use This File

1. Place `CLAUDE.md` in your project root
2. Customize the patterns to match your preferences
3. When using AI assistants, they'll follow these patterns
4. Update it when you learn something new

## About

This template is based on real-world experience building production systems. The patterns focus on maintainability over cleverness, because that's what matters when software is actually being used.

Inspired by [Titus Soporan's blog post](https://tsoporan.com/blog/building-with-claude-code-lessons-learned).

---

_Remember: Good code isn't clever - it's code that works reliably and can be maintained by someone who didn't write it._
