liveBook · Manning

Domain service

As explained in Clean Applications with Hexagonal Architecture

A domain service is a stateless domain-layer component that encapsulates business logic not naturally belonging to a single entity.

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

How Clean Applications with Hexagonal Architecture covers it

How deep it goes
Defines responsibility, placement, and direct testing, while leaving concurrent uniqueness enforcement to persistence.
Examples
Demonstrates generating an article slug and rejecting duplicates against an author's existing slugs.
What it assumes
Assumes the application can supply the relevant existing slugs to the service.
What you can do after
Builds a service directly and tests successful generation and duplicate rejection without mocks or Spring.
How it connects
Connects domain services to aggregates, entities, application services, and persistence adapters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clean Applications with Hexagonal Architecture. The section links point to the parts of the book it draws on.