Skip to main content

Posts

Showing posts with the label Refactoring

Refactoring Anemic Domain Models: Moving Logic from Services to Rich Aggregates

  One of the most pervasive anti-patterns in modern backend development is the   Anemic Domain Model . It often starts innocently: you define your entities as simple data containers (POJOs or POCOs) to play nicely with your ORM. Then, you create a "Service Layer" to handle the business logic. Fast forward six months. Your  OrderService  is 3,000 lines long. Business rules are duplicated across three different handlers. Unit testing requires mocking five different repositories just to verify a status change. This is the  Transaction Script  pattern masquerading as Object-Oriented Programming. In this guide, we will refactor a typical Service-based architecture into a  Rich Domain Model . We will move logic out of the service and into the Aggregate, enforcing invariants where they belong: inside the domain object. The Root Cause: Why Anemia Happens Anemia usually stems from a fundamental misunderstanding of the separation of concerns. Developers often co...

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...