Home > OS >  DDD, should I create a domain service just to save data?
DDD, should I create a domain service just to save data?

Time:09-11

I'm trying to folllow this guide https://www.baeldung.com/hexagonal-architecture-ddd-spring . After reading along I found this interesting approach

Lastly, we should make sure that the Order will be always saved after each action. To do that, we'll define a Domain Service, which usually contains logic that can't be a part of our root:

So from what I understand a domain service is what we use when we can't fit business logic in a single domain object. But what the guide did was just saving a single domain object to the database because we can't have the repository within our domain object right??. If that's the case why don't we just let the controller have access to the repository (some say it's bad practice some say "no" I don't even understand??) since we already put business logic in the domain object. so we would have something like this.

@PostMapping
public Mono<Order> addProduct(Request request) {
    return orderRepository.findById(request.orderId())
                          .map(order -> {
                              order.addProduct(reqeust.getProduct());
                              return order;
                          })
                          .flatMap(order-> orderRepository.save(order));
}.

Should we create an additional layer and call it Domain Service for saving data ? please help me understand best practice.

CodePudding user response:

You definitely do not want any database code in your entities or domain services.

Application Service is a place for operations:

In many cases, Application Services are the interface used by the outside world, where the outside world can’t communicate via our Entity objects, but may have other representations of them. Application Services could map outside messages to internal operations and processes, communicating with services in the Domain and Infrastructure layers to provide cohesive operations for outside clients.

Application services orchestrate calls to repositories and domain objects.

  • Related