When business logic spans multiple aggregates or no single entity should own a calculation, a domain service keeps that rule out of entities with narrower responsibilities. section 3.5
A domain service belongs in the domain layer and contains business rules, not application orchestration. Keep it framework-free and free of infrastructure dependencies; make it a pure function of its inputs where possible. For slug uniqueness, it can compare a candidate against slugs supplied by the application. Persistence should still guard against duplicates created concurrently. section 3.5
Listing 3.12 Bridging business logic through the use of domain services
public class SlugUniquenessService { #A
public Either<DomainError, Slug> generateUniqueSlug( #B
final Title title, final List<Slug> existingSlugs) {
final Slug candidate = Slug.fromTitle(title); #C
if (existingSlugs.contains(candidate)) {
return Either.left(new DomainError( #D
"Slug '" + candidate.value() + "' already exists"));
}
return Either.right(candidate);
}
}
See a Java service that generates a slug and returns either a domain error for a duplicate or the candidate slug. section 3.5
Test the service by constructing it directly and asserting both successful generation and duplicate rejection; these cases need no mocks or Spring context. section 3.5
