Skip to main content

Posts

Showing posts with the label Domain-Driven Design (DDD)

Refactoring Anemic Domain Models: Moving Logic from Services to Entities

  You have likely encountered the "Service Layer" architecture that dominates modern web development. You open a codebase, find an entity named   Order , and it looks like this: export class Order { public id: string; public items: OrderItem[]; public total: number; public status: string; public updatedAt: Date; } It is a glorified database schema definition. It has no behavior, only state. Then, you open  OrderService.ts , and you find a 2,000-line procedural script containing methods like  createOrder ,  calculateTotal ,  cancelOrder , and  validateStock . This is the  Anemic Domain Model . The entity is a data structure, and the service is a transaction script. While this pattern is common, it violates the fundamental principles of Object-Oriented Programming (OOP) and Domain-Driven Design (DDD). It leads to low cohesion (logic regarding an Order is scattered across services) and high coupling (services become dependent on the interna...