Video in progress

How do you add cross-cutting concerns like audit, metrics and permission checks without polluting domain code?

A domain method should only deal with the business rule. I move cross-cutting concerns to the boundary: an application service, a decorator, an aspect or a domain event listener. Which one depends on how tied to the business the concern is: observability is an aspect, an audit with business meaning is an event.

📖 Answer

A polluted domain method looks like this:

public void approve(User by) {
    log.info("approve start {}", id);
    meterRegistry.counter("loan.approve").increment();
    if (!by.hasRole("CREDIT_OFFICER")) throw new AccessDeniedException();
    auditRepo.save(new AuditRecord(...));
    status = APPROVED;                        // the business rule: 1 line
}

The domain object now knows about Micrometer, Spring Security and a repository. To test it you need four mocks.

How I separate them:

Concern Where it goes
Tracing, metrics, slow-method logging an aspect or Micrometer @Observed, at the boundary
Technical permission (does the user have the role) the application service or @PreAuthorize
Business permission ("you can't approve your own application") the domain itself: this is a rule
Business audit ("who approved it, and when") a domain event, and a listener writes it
Retry, timeout a decorator around the adapter (Resilience4j)

The domain version:

public LoanApproved approve(OfficerId by) {
    if (by.equals(applicantId)) throw new SelfApprovalNotAllowed(id);
    status = APPROVED;
    return new LoanApproved(id, by, clock.instant());
}

The application service publishes the event, the audit listener writes it, and the metrics go through an aspect.

There is one catch: if losing an audit record is not legally acceptable (finance), it has to be written in the same transaction (or to an outbox), not by an asynchronous listener. And remember that aspects don't work on self-invocation: don't hang them on methods inside the domain.