Jordan
Jordan

Reputation: 5445

DDD when to isolate side effects into domain services

Say I have a ShippingOrder entity which is composed of, among other things, a RouteSpecification value object.

In order to validate the RouteSpecification I need to make a simple call to a service which calculates the distance - this needs to be done as the route is considered invalid if it does not meet a minimum distance requirement.

Should I be constructing the RouteSpecification inside a RouteSpecificationDomainService or should this simply be used for validation prior to construction of the model?

If it’s the former should this domain service take, as arguments, the components that are required to build the route specification (origin and destination) or should this be abstracted into another domain model that represents an UnvalidatedRouteSpecification and returns a ValidatedRouteSpecification?

If it’s the latter then I just need to trust that it’s used properly by consumers or is there a further abstraction to guard against abuse?

Upvotes: 0

Views: 526

Answers (2)

winson
winson

Reputation: 428

The idomatic DDD answer here would be using a Factory.

A factory in DDD is responsible for constructring a valid Aggregate (with all its containing Entities and Value Objects initialized). The Factory is a component that may use any dependencies (even ones to external systems) necessary to ensure this behaviour.

Since shipping order is your aggregate, the ShippingOrderFactory should be given all arguments and dependencies to construct the object even if they are not used in the final object

Upvotes: 2

jgauffin
jgauffin

Reputation: 101166

If the RouteSpecification is a value object, then no, it should not have its own domain service. Only root aggregates do.

However, the ShippingOrderService can have a GenerateRoute method which takes origin and destination and returns a valid route.

Since the calculation of the route is important, the value object should only have a constructor which takes everything required for it to be in a valid state. In that way it will be impossible to assign an invalid route to the ShippingOrder entity.

Upvotes: 0

Related Questions