When implementing DDD in an application which contains a lot of CRUD functionality, coupled with a web-API of some sort, you end up in a situation where something which could be made relatively simple with the tooling provided by the platform becomes more difficult. For example:
Say we have a User object, and you’re trying hard to not create an anemic domain model, so you have more expressive operations modeled:
class User {
public void terminateAccount(TeminationReason reason);
public void reactivateAccount();
}
The above class is nice, because it lets us mark the account as terminated and set the reason at once. Clearly an improvement over setEnabled(false), and setTerminationReason(..).
The rub is, lets say we have something like a JAX-RS web service which can GET/PUT over that user. The framework (JAX-RS, JAXB) will easily serialize and deserialize our DTO objects for us. Now, where we could’ve previously done:
entity.setEnabled(dto.isEnabled);
entity.setTerminationReason(dto.getTerminationReason);
we have to instead:
if (entity.isEnabled() && !dto.isEnabled()) {
entity.terminateAccount(dto.getTerminationReason);
} else if (!entity.isEnabled && dto.isEnabled) {
entity.reactivateAccount();
}
The big disconnect here being the business oriented interface of the domain object, and the CRUD-style access pattern over a RESTful API. Since both DDD and REST are best practices in their own rights, what lessons has everyone here learned to make the code above less painful/repetitive/etc?
PS – We’re using DTOs because when using an ORM framework behind the scenes, actually serializing the Entities to XML/JSON is problem since we can’t limit the lazy loading. There are also different attributes you typically want to expose over the RESTful API (reference URLs, etc) which don’t belong in the domain model. I’m open to suggestions here too.
I think the issue here is that you’re trying to use a single DTO to represent the
Userentity across all APIs. Instead, if you have a separate DTO for each operation, containing only the required data, your code would be much simpler.For example, the
TerminateAccountAPI would have a DTO with only the termination reason, and your code would simply be: