🏗️ Architecture

Clean Architecture

Clean Architecture

Clean Architecture is a software architecture principle proposed by Robert C. Martin (Uncle Bob) in which dependencies always point inward (toward business logic), allowing code to be written independently of frameworks and databases.

📖 Detailed Explanation

Clean Architecture is an architectural pattern published by Robert C. Martin in 2012 that integrates the core principles of earlier architectures such as Hexagonal Architecture and Onion Architecture. The core idea is the Dependency Rule: "dependencies always point inward."

Frameworks & Drivers (UI, DB, Web)
↓
Interface Adapters (Controllers, Gateways)
↓
Use Cases (Application Business Rules)
↓
Entities (Enterprise Business Rules)

Four concentric layers

Dependency Rule

Source code dependencies must point only inward. Inner circles must know nothing about outer circles. This means:

💻 Code Example

Project structure

src/
├── domain/                    # Entities (핵심 비즈니스 규칙)
│   ├── entities/
│   │   ├── User.ts
│   │   └── Order.ts
│   └── repositories/          # Repository 인터페이스
│       ├── IUserRepository.ts
│       └── IOrderRepository.ts
├── application/               # Use Cases (애플리케이션 규칙)
│   ├── usecases/
│   │   ├── CreateUserUseCase.ts
│   │   └── PlaceOrderUseCase.ts
│   └── dto/
│       ├── CreateUserDTO.ts
│       └── OrderDTO.ts
├── infrastructure/            # Frameworks & Drivers
│   ├── database/
│   │   ├── UserRepository.ts  # Repository 구현
│   │   └── OrderRepository.ts
│   └── web/
│       ├── express/
│       └── controllers/
└── interfaces/                # Interface Adapters
    ├── controllers/
    │   ├── UserController.ts
    │   └── OrderController.ts
    └── presenters/
        └── UserPresenter.ts

Entity layer

// domain/entities/User.ts
export class User {
  private constructor(
    public readonly id: string,
    public readonly email: string,
    private _name: string,
    private _isActive: boolean = true
  ) {
    this.validateEmail(email);
  }

  static create(props: { email: string; name: string }): User {
    return new User(
      crypto.randomUUID(),
      props.email,
      props.name
    );
  }

  static reconstitute(props: {
    id: string; email: string; name: string; isActive: boolean;
  }): User {
    return new User(props.id, props.email, props.name, props.isActive);
  }

  get name(): string { return this._name; }
  get isActive(): boolean { return this._isActive; }

  changeName(newName: string): void {
    if (!newName || newName.length < 2) {
      throw new Error('Name must be at least 2 characters');
    }
    this._name = newName;
  }

  deactivate(): void {
    this._isActive = false;
  }

  private validateEmail(email: string): void {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      throw new Error('Invalid email format');
    }
  }
}

Repository interface (Domain Layer)

// domain/repositories/IUserRepository.ts
import { User } from '../entities/User';

export interface IUserRepository {
  findById(id: string): Promise<User | null>;
  findByEmail(email: string): Promise<User | null>;
  save(user: User): Promise<void>;
  delete(id: string): Promise<void>;
}

// 의존성 규칙: 도메인은 인터페이스만 정의
// 실제 구현은 infrastructure에서 담당

Use Case layer

// application/usecases/CreateUserUseCase.ts
import { User } from '../../domain/entities/User';
import { IUserRepository } from '../../domain/repositories/IUserRepository';

export interface CreateUserDTO {
  email: string;
  name: string;
}

export interface CreateUserOutputDTO {
  id: string;
  email: string;
  name: string;
}

export class CreateUserUseCase {
  // 의존성 주입: 인터페이스에 의존
  constructor(private userRepository: IUserRepository) {}

  async execute(input: CreateUserDTO): Promise<CreateUserOutputDTO> {
    // 비즈니스 규칙: 이메일 중복 검사
    const existingUser = await this.userRepository.findByEmail(input.email);
    if (existingUser) {
      throw new Error('Email already exists');
    }

    // 엔티티 생성 (도메인 규칙 적용)
    const user = User.create({
      email: input.email,
      name: input.name,
    });

    // 영속화
    await this.userRepository.save(user);

    // Output DTO 반환
    return {
      id: user.id,
      email: user.email,
      name: user.name,
    };
  }
}

Repository implementation (Infrastructure Layer)

// infrastructure/database/UserRepository.ts
import { User } from '../../domain/entities/User';
import { IUserRepository } from '../../domain/repositories/IUserRepository';
import { PrismaClient } from '@prisma/client';

export class PrismaUserRepository implements IUserRepository {
  constructor(private prisma: PrismaClient) {}

  async findById(id: string): Promise<User | null> {
    const data = await this.prisma.user.findUnique({ where: { id } });
    if (!data) return null;

    return User.reconstitute({
      id: data.id,
      email: data.email,
      name: data.name,
      isActive: data.isActive,
    });
  }

  async findByEmail(email: string): Promise<User | null> {
    const data = await this.prisma.user.findUnique({ where: { email } });
    if (!data) return null;

    return User.reconstitute({
      id: data.id,
      email: data.email,
      name: data.name,
      isActive: data.isActive,
    });
  }

  async save(user: User): Promise<void> {
    await this.prisma.user.upsert({
      where: { id: user.id },
      update: { name: user.name, isActive: user.isActive },
      create: {
        id: user.id,
        email: user.email,
        name: user.name,
        isActive: user.isActive,
      },
    });
  }

  async delete(id: string): Promise<void> {
    await this.prisma.user.delete({ where: { id } });
  }
}

Controller (Interface Adapter)

// interfaces/controllers/UserController.ts
import { Request, Response } from 'express';
import { CreateUserUseCase } from '../../application/usecases/CreateUserUseCase';

export class UserController {
  constructor(private createUserUseCase: CreateUserUseCase) {}

  async createUser(req: Request, res: Response): Promise<void> {
    try {
      const { email, name } = req.body;

      const result = await this.createUserUseCase.execute({ email, name });

      res.status(201).json({
        success: true,
        data: result,
      });
    } catch (error) {
      if (error instanceof Error) {
        res.status(400).json({
          success: false,
          error: error.message,
        });
      }
    }
  }
}

Dependency injection setup

// main.ts (Composition Root)
import { PrismaClient } from '@prisma/client';
import { PrismaUserRepository } from './infrastructure/database/UserRepository';
import { CreateUserUseCase } from './application/usecases/CreateUserUseCase';
import { UserController } from './interfaces/controllers/UserController';

// 의존성 조립 (바깥에서 안쪽으로 주입)
const prisma = new PrismaClient();
const userRepository = new PrismaUserRepository(prisma);
const createUserUseCase = new CreateUserUseCase(userRepository);
const userController = new UserController(createUserUseCase);

// Express 라우터 설정
app.post('/users', (req, res) => userController.createUser(req, res));

💬 Real-world conversation examples

👨‍💼 PM

"We need to switch our service database from MySQL to PostgreSQL. How long will it take?"

👩‍💻 Backend developer

"We designed it with Clean Architecture, so we only need to swap the Repository implementation. There's no need to touch the business logic. The interface is the same, so we just create a new PostgresUserRepository and change the DI configuration."

👨‍💻 Junior developer

"Can't we call Prisma directly from the Use Case? The code would be simpler..."

👩‍💻 Senior developer

"That violates the Dependency Rule. If the Use Case depends directly on Prisma, you have to modify the business logic whenever the DB changes. If you abstract through a Repository interface, it's easy to replace with a Mock in tests, and you're free to change the ORM."

👨‍💼 Architect

"The domain in this project is complex, so let's go with Clean Architecture. By separating Entities and Use Cases, we can define business rules clearly, and even if we need to replace the framework later, the core logic stays protected."

⚠️ Cautions

Beware of over-abstraction: Applying Clean Architecture to a small project becomes over-engineering. For simple, CRUD-centric services it can actually reduce productivity.

Cost of data conversion between layers: Multiple mappings such as Entity → DTO → Response are needed. This process can be tedious and increase boilerplate code.

Watch for Dependency Rule violations: If an inner layer (Entity, Use Case) imports from an outer layer (Infrastructure), it violates the Dependency Rule. Always abstract through interfaces.

Tip: Adjust the layers to fit the project's complexity. Not every project needs four layers. The key is to keep the "direction of dependencies."

🔗 Related Terms

📚 Learn More