Object-oriented – How to decide whether to implement an operation as Entity operation vs Service operation in Domain Driven Design

Architecturedomain-driven-designobject-orientedservices

I am reading Evans's Domain Driven Design. The book says that there are entity and there are services. If I were to implement an operation, how to decide whether I should add it as a method on an entity or do it in a service class?

e.g. myEntity.DoStuff() or myService.DoStuffOn(myEntity)?

Does it depend on whether other entities are involved? If it involves other entities, implement as service operation? But entities can have associations and can traverse it from there too right?

Does it depend on stateless or not? But service can also access entities' variable, right? Like in do stuff myService.DoStuffOn, it can have code like

if(myEntity.IsX) doSomething();

Which means that it will depend on the state?

Or does it depend on complexity? How do you define complex operations?

Best Answer

Does it depend on whether other entities are involved? If it involves other entities, implement as service operation?

This is one good rule of thumb. Another: logic that describes a fundamental fact about the entity and is used in multiple use cases probably belongs into the entity. Logic that is use case specific probably doesn't. Both of these are variants of the Single Responsibility Principle.

But entities can have associations and can traverse it from there too right?

Yes, but entities should not be tightly coupled like that. Except perhaps in cases where one entity "contains" another and they are already tightly coupled conceptually.

Or does it depend on complexity? How do you define complex operations?

That's just a basic rule of code cleanliness: if a piece of code becomes too large and complex, break it up. If you have an operation as part of an entitry that containes more code than the rest of the entity together and you've already had to refactor it into sub-operations, you should think about moving it out of the entity entirely.

Related Topic