# Coding Standards Skill

> **Language-specific best practices for Python and TypeScript/JavaScript.**

---

## Core Principles

### KISS (Keep It Simple, Stupid)
- Prefer straightforward solutions
- Avoid premature optimization
- Code should be readable at a glance

### DRY (Don't Repeat Yourself)
- Extract common logic into functions
- Use configuration over duplication
- But: Don't over-abstract prematurely

### YAGNI (You Aren't Gonna Need It)
- Build what's needed now
- Don't design for hypothetical futures
- Remove unused code

### Immutability
- Prefer immutable data structures
- Use `const` / `final` by default
- Return new objects instead of mutating

---

## Python Standards

### File Size
- Maximum **800 lines** per file
- If larger: extract to submodules

### Type Hints (Required)
```python
def process_data(
    data: pd.DataFrame,
    threshold: float = 0.8
) -> tuple[pd.DataFrame, list[str]]:
    """Process and return (result, errors)."""
    ...
```

### Error Handling
```python
# ✅ Specific exceptions
try:
    result = operation()
except ValueError as e:
    raise ValidationError(f"Invalid: {e}") from e

# ❌ Generic exceptions
try:
    result = operation()
except Exception:  # Too broad
    pass
```

### Logging (No print())
```python
import structlog
logger = structlog.get_logger()

logger.info("operation_started", item_id=item_id)
```

### Dataclasses
```python
@dataclass(frozen=True)  # Immutable
class User:
    id: str
    email: str
    created_at: datetime
```

---

## TypeScript Standards

### File Size
- Maximum **800 lines** per file
- Split large components into smaller ones

### Strict Mode
```json
{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true
  }
}
```

### Type Safety
```typescript
// ✅ Explicit types
const users: User[] = await fetchUsers();

// ❌ Implicit any
const users = await fetchUsers();
```

### Immutability
```typescript
// ✅ Readonly
interface User {
  readonly id: string;
  readonly email: string;
}

// ✅ Const assertions
const CONFIG = {
  timeout: 5000,
  retries: 3,
} as const;
```

### Error Handling
```typescript
// ✅ Type-safe errors
class ValidationError extends Error {
  constructor(message: string, public readonly field: string) {
    super(message);
    this.name = 'ValidationError';
  }
}
```

---

## React Standards

### Component Size
- Max 150 lines per component
- Extract logic to custom hooks
- Extract UI to sub-components

### Hooks Rules
```typescript
// ✅ Correct dependency arrays
useEffect(() => {
  fetchData(userId);
}, [userId]);  // Include all dependencies

// ❌ Missing dependencies
useEffect(() => {
  fetchData(userId);
}, []);  // userId should be included
```

### State Management
```typescript
// ✅ Derived state
const total = useMemo(
  () => items.reduce((sum, item) => sum + item.price, 0),
  [items]
);

// ❌ Redundant state
const [total, setTotal] = useState(0);
useEffect(() => {
  setTotal(items.reduce(...));
}, [items]);
```

---

## Related Skills

- [backend-patterns](../backend-patterns/) - API design
- [frontend-patterns](../frontend-patterns/) - React patterns
- [tdd-workflow](../tdd-workflow/) - Testing practices
