# AI-Friendly Naming Conventions

## Overview

This document provides comprehensive naming conventions optimized for AI agent understanding and collaboration. Good naming is crucial for AI agents to understand code context, purpose, and relationships.

## The Cardinal Sin: _refactored

### Never Use _refactored ❌

This is the #1 rule for AI agents. The `_refactored` suffix creates massive confusion:

```python
# NEVER DO THIS
config.py → config_refactored.py
handler.py → handler_refactored.py

# This creates questions:
# - Which file is current?
# - Should imports use the new file?
# - Why are both files present?
# - Which will be maintained?
```

### Alternatives to _refactored ✅

```python
# Option 1: Modify in place (PREFERRED)
# Edit config.py directly

# Option 2: Version numbering (for breaking changes)
api.py → api_v2.py  # Clear version

# Option 3: Feature-based naming (for different purposes)
config.py → config_minimal.py  # Different use case
```

## File Naming Conventions

### Python Files

#### General Rules
- Use lowercase with underscores
- Be descriptive but concise
- Avoid redundant suffixes
- Group related files with prefixes

#### Good Examples ✅
```
user_authentication.py    # Clear purpose
payment_processor.py      # Specific functionality
database_connection.py    # Infrastructure component
email_validator.py        # Single responsibility
```

#### Bad Examples ❌
```
userAuth.py              # Wrong case style
payment_processor_new.py # Avoid state in names
db_conn.py              # Too abbreviated
utils.py                # Too generic
helpers.py              # Too vague
stuff.py                # Meaningless
```

### Directory Names

#### Structure Examples
```
project/
├── handlers/           # Plural for collections
├── models/            # Domain objects
├── validators/        # Specific purpose
├── processors/        # Action-based naming
├── core/              # Central functionality
└── utils/             # Truly generic utilities
```

#### Avoid These Patterns ❌
```
handlers_new/          # No state in names
handlers_v2/           # Use git for versions
temp/                  # Nothing is temporary
old/                   # Version control handles this
backup/                # Use proper backups
```

### Test Files

#### Naming Pattern
```
# Mirror the source file with test_ prefix
src/user_handler.py → tests/test_user_handler.py
src/payment/processor.py → tests/payment/test_processor.py
```

#### Test Directory Structure
```
tests/
├── unit/              # Unit tests
├── integration/       # Integration tests
├── fixtures/          # Test data
├── conftest.py        # Pytest configuration
└── __init__.py        # Package marker
```

## Class Naming

### General Classes

#### Use PascalCase
```python
# Good ✅
class UserAuthenticator:
    pass

class PaymentProcessor:
    pass

class DatabaseConnection:
    pass

# Bad ❌
class user_authenticator:  # Wrong case
    pass

class UserAuth:  # Too abbreviated
    pass

class UA:  # Meaningless abbreviation
    pass
```

### Descriptive Suffixes

Use suffixes that describe the pattern or responsibility:

```python
# Patterns
class UserFactory:          # Creates instances
class UserBuilder:          # Complex construction
class UserManager:          # Lifecycle management
class UserRepository:       # Data access
class UserService:          # Business logic
class UserController:       # Request handling
class UserValidator:        # Validation logic
class UserSerializer:       # Data transformation

# Bad suffixes ❌
class UserHandler:          # Too generic
class UserUtil:            # Unclear purpose
class UserHelper:          # Vague responsibility
class UserThing:           # Meaningless
```

### Abstract Classes and Interfaces

```python
# Abstract base classes
class BaseAuthenticator(ABC):
    pass

class AbstractProcessor(ABC):
    pass

# Interfaces (Python doesn't have interfaces, but we can indicate intent)
class AuthenticatorInterface(Protocol):
    pass

# Or simpler
class IAuthenticator(Protocol):  # 'I' prefix for interface
    pass
```

## Function and Method Naming

### Use snake_case

```python
# Good ✅
def authenticate_user(username: str, password: str) -> User:
    pass

def calculate_total_price(items: List[Item]) -> Decimal:
    pass

def send_notification_email(user: User, message: str) -> None:
    pass

# Bad ❌
def authenticateUser():     # camelCase
    pass

def calc_tot():            # Too abbreviated
    pass

def doStuff():             # Meaningless
    pass
```

### Action-Oriented Naming

Functions should start with verbs:

```python
# Good action verbs ✅
def get_user_by_id(user_id: int) -> User:
    """Retrieve without side effects."""

def create_user(data: dict) -> User:
    """Create new resource."""

def update_user_profile(user: User, data: dict) -> User:
    """Modify existing resource."""

def delete_expired_sessions() -> int:
    """Remove resources."""

def validate_email_format(email: str) -> bool:
    """Check validity."""

def calculate_tax_amount(price: Decimal) -> Decimal:
    """Compute values."""

def process_payment(payment: Payment) -> PaymentResult:
    """Execute complex operation."""
```

### Boolean Functions

Use prefixes that indicate boolean return:

```python
# Good boolean prefixes ✅
def is_valid_email(email: str) -> bool:
    pass

def has_permission(user: User, action: str) -> bool:
    pass

def can_access_resource(user: User, resource: Resource) -> bool:
    pass

def should_retry_operation(error: Exception) -> bool:
    pass

# Bad ❌
def valid_email(email: str) -> bool:  # Unclear if checking or making valid
    pass

def check_permission(user: User) -> bool:  # 'check' is vague
    pass
```

## Variable Naming

### General Variables

```python
# Good ✅
user_count = len(users)
is_authenticated = user.is_authenticated()
max_retry_attempts = 3
connection_timeout = 30.0
email_address = "user@example.com"

# Bad ❌
cnt = len(users)           # Too abbreviated
flag = True                # What flag?
temp = calculate_value()   # Temporary is meaningless
data = fetch_data()        # Too generic
x = 42                     # Unless in math context
```

### Collections

Be specific about collection contents:

```python
# Good ✅
active_users = []          # Plural, descriptive
payment_records = {}       # Clear content type
email_addresses = set()    # Specific data
user_id_to_name = {}      # Clear mapping

# Bad ❌
users_list = []           # Redundant type suffix
dict_data = {}            # Generic name
items = []                # Too vague
temp_list = []            # Avoid 'temp'
```

### Constants

```python
# Use UPPER_SNAKE_CASE
MAX_LOGIN_ATTEMPTS = 5
DEFAULT_TIMEOUT_SECONDS = 30
API_VERSION = "2.0"
DATABASE_CONNECTION_POOL_SIZE = 10

# Group related constants
class PaymentStatus:
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"
    REFUNDED = "refunded"
```

## Special Naming Patterns

### Private Members

```python
class UserService:
    def __init__(self):
        self._cache = {}            # Single underscore for internal
        self.__secret_key = "..."   # Double underscore for name mangling
    
    def _validate_input(self, data):  # Internal method
        pass
    
    def public_method(self):          # Public API
        pass
```

### Type Variables

```python
from typing import TypeVar, Generic

# Simple type variables
T = TypeVar('T')
K = TypeVar('K')
V = TypeVar('V')

# Descriptive type variables
UserType = TypeVar('UserType', bound=User)
NumericType = TypeVar('NumericType', int, float, Decimal)

# Generic class
class Repository(Generic[T]):
    def get(self, id: int) -> T:
        pass
```

### Enums

```python
from enum import Enum, auto

class UserRole(Enum):
    ADMIN = "admin"
    USER = "user"
    GUEST = "guest"

class OrderStatus(Enum):
    PENDING = auto()
    PROCESSING = auto()
    SHIPPED = auto()
    DELIVERED = auto()
```

## Module and Package Naming

### Package Structure

```python
storm_logger/              # Main package (lowercase, underscore)
├── __init__.py
├── core/                  # Subpackage
│   ├── __init__.py
│   ├── logger.py         # Core module
│   └── formatters.py
├── handlers/             # Feature-based grouping
│   ├── __init__.py
│   ├── file_handler.py
│   └── stream_handler.py
└── utils/                # Utilities
    ├── __init__.py
    ├── validators.py
    └── sanitizers.py
```

### Import Naming

```python
# Standard imports
import os
import sys
from pathlib import Path

# Third-party imports
import requests
from django.conf import settings

# Relative imports with clear names
from .models import User, Payment
from .validators import validate_email, validate_phone
from ..utils import format_currency

# Avoid these ❌
from .utils import *      # No wildcard imports
import helpers as h       # Unclear abbreviation
from . import stuff      # Meaningless name
```

## Database-Related Naming

### Models and Tables

```python
# Django model example
class User(models.Model):  # Singular for models
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'users'  # Plural for tables

# Table naming
users                # Plural, lowercase
user_profiles        # Snake case for multi-word
payment_transactions # Descriptive
```

### Field Naming

```python
# Good field names ✅
created_at          # Timestamp convention
updated_at          # Consistency
is_active           # Boolean prefix
has_verified_email  # Clear boolean
user_id             # Foreign key convention
total_amount        # No abbreviations

# Bad field names ❌
created            # Ambiguous
flag               # What flag?
amt                # Too abbreviated
usr_id             # Unnecessary abbreviation
```

## API and URL Naming

### RESTful Endpoints

```python
# Good endpoints ✅
/api/v1/users                    # Plural resources
/api/v1/users/{id}              # Specific resource
/api/v1/users/{id}/orders       # Nested resources
/api/v1/auth/login              # Clear action

# Bad endpoints ❌
/api/getUsers                   # Not RESTful
/api/user-list                  # Inconsistent style
/api/UserData                   # Wrong case
/api/v1/temp                    # Meaningless
```

### URL Parameters

```python
# Query parameters (snake_case)
/api/users?sort_by=created_at&page_size=20

# Path parameters (descriptive)
/api/users/{user_id}/posts/{post_id}

# Consistent naming
start_date, end_date    # Not from, to
page_size, page_number  # Not limit, offset
```

## Common Anti-Patterns

### 1. State in Names ❌
```python
# Never encode state in names
config_old.py
config_new.py
config_backup.py
handler_temp.py
processor_broken.py
```

### 2. Version Numbers in Code ❌
```python
# Avoid version numbers except for APIs
function_v2()
UserHandlerV3
process_data_new()
```

### 3. Meaningless Abbreviations ❌
```python
# Don't over-abbreviate
ctx → context
cfg → config
usr → user
msg → message
evt → event

# Acceptable abbreviations
id → identifier (universally understood)
url → uniform resource locator
api → application programming interface
```

### 4. Hungarian Notation ❌
```python
# Don't include type in name
strName = "John"      # Bad
intAge = 25          # Bad
listUsers = []       # Bad

# Good
name = "John"
age = 25
users = []
```

### 5. Generic Names ❌
```python
# Avoid these generic names
data
info
temp
obj
thing
stuff
utils (unless truly generic utilities)
helpers
manager (unless managing lifecycle)
handler (unless handling specific events)
```

## AI Agent Specific Guidelines

### 1. Clarity for Context Understanding
AI agents need clear names to understand context:
```python
# Clear context
class UserAuthenticationService:
    def verify_user_credentials(self, username: str, password: str) -> bool:
        pass

# Unclear context
class Service:
    def check(self, u: str, p: str) -> bool:
        pass
```

### 2. Avoid Ambiguity
```python
# Unambiguous
def calculate_order_total_with_tax(order: Order) -> Decimal:
    pass

# Ambiguous
def process(order: Order) -> Decimal:  # Process how?
    pass
```

### 3. Self-Documenting Names
```python
# Self-documenting
is_valid_credit_card_number(number: str) -> bool
send_password_reset_email(user: User) -> None
calculate_compound_interest(principal: Decimal, rate: float, years: int) -> Decimal

# Requires additional context
validate(number: str) -> bool
send(user: User) -> None
calculate(p: Decimal, r: float, t: int) -> Decimal
```

## Summary Checklist

Before finalizing names, ensure:

- [ ] No `_refactored`, `_temp`, `_old`, `_new` suffixes
- [ ] Clear, descriptive names that explain purpose
- [ ] Consistent case style (snake_case, PascalCase)
- [ ] No unnecessary abbreviations
- [ ] Action-oriented function names
- [ ] Boolean functions use is_, has_, can_, should_
- [ ] Collections use plural names
- [ ] Constants use UPPER_SNAKE_CASE
- [ ] No type information in names (no strName)
- [ ] No generic names (data, info, stuff)
- [ ] Self-documenting without requiring comments

Remember: Good names make code self-documenting and help AI agents understand your intentions without ambiguity.