Hmm, this is a complex architectural refactoring question that requires a structured, incremental approach. The user wants to move business logic from controllers to domain layer (aggregate roots/application services), which is a classic DDD and clean architecture refactoring.
I need to provide a practical roadmap, not just theory. The user likely faces a legacy codebase with "fat controllers" and wants to gradually extract domain logic without breaking things. Key concerns would be minimizing risk, maintaining functionality, and ensuring team alignment.
I should structure this as phases, with clear principles first. The core principle is "controllers orchestrate, domain decides." Then break it into concrete steps: assessment, infrastructure prep, iterative extraction, validation. Must emphasize testing since moving logic risks altering behavior.
Need to warn about common pitfalls like over-engineering or extracting too much at once. Should include concrete examples (e.g., "CreateOrder" flow) to illustrate transformation. Also mention team communication since this is as much about people as code.
The roadmap should feel actionable - maybe use a table format for phases with goals, activities, and outcomes. Stress that domain experts must validate logic during extraction, not just developers. Avoid jargon but stay precise.
Excellent goal. Moving logic from anemic controllers into a proper domain layer is a critical step toward building maintainable, scalable, and business-aligned systems. Here is a practical, incremental roadmap for a domain service extraction.
Core Principle to Guide the Effort
Controllers/API Layer = Orchestration & Delivery. Domain Layer (Aggregates & Application Services) = Business Rules & Invariants.
The controller should be thin: validate input, authenticate, call an Application Service, and format the response. All business logic lives in the domain.
Phase 0: Foundation & Assessment (1-2 Weeks)
Goal: Establish a shared understanding and baseline.
Inventory & Categorize: List all controller actions. For each, tag the primary business concept (e.g., CreateOrder, ApproveUser, CalculateInvoice).
Identify "Hotspots": Find controllers that are:
Very long (100+ lines).
Have complex conditional logic.
Call multiple repository methods.
Contain validation beyond simple schema checks (e.g., "user must be active and have a verified email to place this order").
Define Boundaries: Sketch your current bounded contexts (e.g., Sales, Inventory, UserManagement). This will guide where extracted logic belongs.
Tooling & Standards:
Testing: Ensure you have a robust suite of integration/functional tests for critical user journeys before you start moving code. This is your safety net.
Code Review Checklist: Create a checklist for PRs that extract logic (e.g., "Are all business rules now in the domain?", "Is the controller under 20 lines?", "Are unit tests added for the new domain method?").
Communication: Align the team on the "why" and the phased approach. No big-bang rewrites.
Phase 1: Prepare the Domain Layer (2-3 Weeks)
Goal: Create the target structures (Aggregates, Application Services, Value Objects) without yet moving logic.
Define Aggregate Roots: For each hotspot, identify the natural aggregate root (e.g., Order, User, Invoice). Start with 2-3 key aggregates.
Create Skeleton Application Services:
java
// BEFORE (Controller has logic)
@PostMapping("/orders")
public OrderDTO createOrder(@RequestBody CreateOrderRequest req) {
// 50 lines of: validate stock, check user credit, calculate tax, create order...
}
// AFTER Skeleton
@Service
public class OrderApplicationService {
private final OrderRepository orderRepo;
private final InventoryService inventorySvc;
private readonly UserRepository userRepo;
public OrderDTO createOrder(CreateOrderCommand command) {
// 1. Orchestrate domain objects
// 2. Delegate to Order aggregate
// 3. Return DTO
}
}
Design Command/Query Separation: Define Command objects (for writes: CreateOrderCommand) and Query objects (for reads). This formalizes the input for application services.
Establish Shared Kernel: Identify common logic (e.g., Money, EmailAddress, PhoneNumber) and move it to Value Objects in a shared domain module.
Phase 2: Iterative Extraction - The "Strangler Fig" Pattern (Ongoing)
Goal: Incrementally pull logic from controllers into the domain, one use case at a time.
Strategy: Pick one controller action (from your "hotspot" list) per sprint/iteration.
Step-by-Step Extraction for a Single Use Case (e.g., POST /orders):
Write the Failing Domain Test First: Before touching the controller, write a unit test for the new domain method (on Order or OrderApplicationService). This test should capture the business rules.
java
@Test
void createOrder_shouldThrowError_whenUserIsBlacklisted() {
User blacklistedUser = new User(...).blacklist();
Order order = Order.create(blacklistedUser, items);
assertThrows(UserBlacklistedException.class, order::validate);
}
Extract to an Application Service (Orchestration):
Move high-level coordination (e.g., "check inventory, then create order") from the controller to a new method in OrderApplicationService.
Keep the controller logic for now, but have it delegate to the new service method.
Controller becomes:
java
@PostMapping("/orders")
public OrderDTO createOrder(@RequestBody CreateOrderRequest req) {
// 1. Basic HTTP/schema validation (remains)
CreateOrderCommand command = mapper.toCommand(req);
// 2. DELEGATE - now the real work is here
return orderApplicationService.createOrder(command);
}
Extract to the Aggregate Root (Invariants & Logic):
For rules that belong inside the aggregate (e.g., "cannot add an item if order is Shipped", "total must be > 0"), create methods on the Order aggregate (addItem(), calculateTotal()).
The OrderApplicationService now creates the Order aggregate and calls its methods.
Ensure the aggregate enforces its invariants and throws domain exceptions.
Extract Supporting Domain Concepts:
Money → Value Object.
InventoryCheck → Domain Service (if it's logic that doesn't naturally belong to or ).
Phase 3: Strengthen & Polish (1-2 Sprints)
Goal: Mature the new domain model and remove legacy artifacts.
Repository Interface Migration: Shift repository usage from controllers to application services/aggregates. The domain should only depend on interfaces (e.g., OrderRepository), with implementations in the infrastructure layer.
Event-Driven Refinement: Identify natural domain events (OrderShipped, PaymentFailed) and publish them from aggregates. Decouple side-effects (email, notification, analytics) via event handlers.
Review Anemic Domain: Hunt for getters/setters on aggregates. If you find them, ask "does this data/behavior belong here?" and refactor into proper methods or value objects.
Purge Old Code: Once all logic for a given aggregate is extracted and tested, remove:
Direct repository calls from controllers.
Static utility classes that contained business logic.
Redundant DTOs used only for domain logic (use Commands/Queries instead).
Phase 4: Institutionalize & Scale
Goal: Make this the standard way of working.
Create Archetypes/Guides: Document the new patterns (Application Service structure, Aggregate guidelines, Event conventions) with concrete examples from your codebase.
Onboarding: Train new hires on the "clean" architecture.
Code Review Ritual: Make "logic in controllers" an automatic "needs work" review comment.
Architectural Decision Records (ADRs): Record key decisions (e.g., "We use Command/Query separation for all application service inputs").
Common Pitfalls & Mitigation
Pitfall
Mitigation
Over-Engineering: Creating too many domain services or aggregates too early.
Start simple. A single Order aggregate is fine. Extract domain services only when logic spans multiple aggregates or is truly domain-wide.
Leaky Abstractions: Domain logic still depends on Spring/Web annotations (e.g., @Transactional on aggregates).
Keep domain layer pure (Java/Kotlin/your language). Apply cross-cutting concerns (transactions, security) at the application service or infrastructure layer.
Transactional Boundaries Confusion: Where does a transaction start/end?
Typically at the Application Service method level. One method = one unit of work. Use @Transactional on the service class/method, not the controller.
Fear of Breaking Things: Hesitation to extract.
Your integration test suite is your insurance policy. Run it constantly. Extract one small piece, run tests, commit.
" God Application Service": The new service becomes just as fat as the old controller.
If OrderApplicationService.createOrder gets too long, you might need a domain service or the logic belongs in the Order aggregate. The service should orchestrate, not implement rules.
Example Transformation: CreateOrder Flow
Before (Anemic Controller):
java
@PostMapping("/orders")
public OrderDTO createOrder(@RequestBody CreateOrderRequest req) {
// 1. Validate user (repo call)
User user = userRepo.findById(req.getUserId());
if (user == null || !user.isActive()) throw ...;
// 2. Validate & reserve inventory (service call)
InventoryReservation reservation = inventory.reserve(req.getItems());
if (!reservation.isSuccessful()) throw ...;
// 3. Calculate totals (domain logic in controller)
BigDecimal total = req.getItems().stream()
.map(i -> i.getPrice().multiply(BigDecimal.valueOf(i.getQuantity())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal tax = total.multiply(TAX_RATE);
// 4. Create Order entity (anemic)
Order order = new Order();
order.setId(generator.next());
order.setUser(user);
order.setItems(reservation.getItems());
order.setTotal(total);
order.setTax(tax);
order.setStatus(OrderStatus.CREATED);
orderRepo.save(order);
// 5. Send email (side-effect in controller)
emailService.sendOrderConfirmation(user.getEmail(), order.getId());
return mapper.toDTO(order);
}
After (Domain-Centric):
java
// Controller (Thin)
@PostMapping("/orders")
public OrderDTO createOrder(@RequestBody CreateOrderRequest req) {
CreateOrderCommand command = mapper.toCommand(req);
OrderDTO order = orderApplicationService.createOrder(command);
return order; // Already mapped inside service or via a dedicated query
}
// Application Service (Orchestration)
@Service
@Transactional
public class OrderApplicationService {
public OrderDTO createOrder(CreateOrderCommand command) {
// 1. Find Aggregate (User is a separate aggregate)
User user = userRepository.findById(command.getUserId())
.orElseThrow(() -> new UserNotFoundException(command.getUserId()));
user.assertCanPlaceOrder(); // Domain validation on User aggregate
// 2. Create & Configure Aggregate (All logic inside Order)
Order order = new Order(command.getOrderId(), user);
order.addItems(command.getItems()); // Validates stock, calculates line totals
order.calculateTotal(); // Applies tax rules, etc.
order.confirm(); // Changes state, might publish OrderPlacedEvent
// 3. Save
orderRepository.save(order);
// 4. Return DTO (or, better, return Order ID and let a query fetch the DTO)
return mapper.toDTO(order);
}
}
// Order Aggregate (Core Logic)
public class Order {
public void addItems(List<OrderItem> items) {
// Core invariant: Can't add items if already shipped.
if (this.status == OrderStatus.SHIPPED) {
throw new IllegalStateException("Cannot modify shipped order");
}
// For each item, check with Inventory domain service (passed in or static)
items.forEach(item -> {
inventoryService.reserve(item.getSku(), item.getQuantity());
this.items.add(new OrderItem(item));
});
}
public void calculateTotal() {
this.total = this.items.stream()
.map(OrderItem::getExtendedPrice)
.reduce(BigDecimal.ZERO, BigDecimal::add);
this.tax = this.total.multiply(taxPolicy.calculateFor(this.user));
}
public void confirm() {
this.status = OrderStatus.CONFIRMED;
DomainEventPublisher.publish(new OrderPlacedEvent(this.id, this.user.getId()));
}
}
Final Checklist for Your Roadmap
Team Alignment: Everyone agrees on the goal and the incremental approach.
Safety Net: Comprehensive integration/functional tests for key journeys.
Clean Controller Pattern: No business logic, only HTTP/API concerns.
Documentation & Onboarding: New patterns are documented and shared.
This roadmap turns a daunting refactoring into a manageable, low-risk, value-delivering process. Start small, test fiercely, and celebrate each extracted use case. The momentum will build as the codebase becomes dramatically more understandable and flexible.
Inventory
Order
OrderConfirmationEmail → Domain Event (OrderPlacedEvent), published by the aggregate/application service and handled by an infrastructure handler.
Refactor & Rename:
Controller now only handles HTTP concerns: auth, request validation, mapping to command, delegating, mapping response.
Rename controller method if needed to reflect its new role (e.g., createOrder is fine, but its body is now trivial).
Update & Run Tests: Your integration test should still pass. Unit tests now cover the new domain code.