---
name: layered
description: This skill should be used when the user asks about "layered architecture", "n-tier architecture", "when to use layered", "separate layers", "presentation business data", or mentions needing to organize code into horizontal layers.
version: 1.0.0
---

# Layered Architecture Pattern

## What Is It
Layered Architecture organizes code into horizontal layers, each with a specific responsibility. Common layers include Presentation, Business Logic, and Data Access. Each layer only depends on the layer directly below it, promoting separation of concerns.

## When to Use
- **Enterprise applications** - Traditional business applications
- **Team specialization** - Different teams for different layers
- **Clear separation** - Need to isolate concerns
- **Legacy systems** - Gradual migration path
- **Standard architecture** - Well-understood pattern

## When NOT to Use
- **Simple applications** - Overhead not justified
- **Microservices** - Service-per-layer can be anti-pattern
- **High performance** - Layer hopping adds latency
- **Rapid prototyping** - Strict layering slows iteration

## How to Implement

### Implementation Steps
1. Define layers with clear responsibilities
2. Establish interfaces between layers
3. Enforce unidirectional dependencies (top to bottom)
4. Keep layers independent and testable
5. Consider cross-cutting concerns (logging, security)

### TypeScript Implementation

```typescript
// Presentation Layer
class UserController {
  constructor(private userService: UserService) {}

  async getUser(req: Request): Promise<Response> {
    const user = await this.userService.getUser(req.params.id);
    return { status: 200, body: user };
  }
}

// Business Layer
class UserService {
  constructor(private userRepo: UserRepository) {}

  async getUser(id: string): Promise<UserDTO> {
    const user = await this.userRepo.findById(id);
    return this.toDTO(user);
  }
}

// Data Access Layer
class UserRepository {
  async findById(id: string): Promise<User> {
    return db.query('SELECT * FROM users WHERE id = ?', [id]);
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/layered.ts` - Basic implementation with 3 layers
- `examples/layered-advanced.ts` - Real-world example with 4 layers

## Related Patterns
- **MVC** - Presentation layer often uses MVC
- **Repository** - Data layer often uses Repository
- **Service Layer** - Business layer pattern
