Java – Service layer with DTO

Architectureentityjavaormrepository

I'm refactoring my desing to use a service layer – however I'm confused about how you would pass arguments, when it's only allowed to update certain fields of the entity. For instance I have some fields which are only allowed to be set at creation (meta data). But every examples I see about service layer takes the entity as argument, eg. update(Entity entity), where all the values possibly could have been changed. If I only want to make it possible to add orders (and not modifying anything else for the customer). This could be done by:

customer.add(new Order())
service.update(customer)

which looks very nice, however I could change other fields in the customer without this being noticed by the service.
My alternative would by something like:

service.addOrder(customer, new Order())

This seems reasonable. However this could possibly create methods with very long parameterlists (bad) and also loading the same entity twice (both in servicelayer and in where it is used before).
Would it be better to simply create DTO's and methods for every partial update of the entity? This would also require either the service layer or repository to load the (possibly) already loaded entity from the database.

Best Answer

While you could make both of those functionally do the same thing, they do not suggest the same thing.

The first suggests that add an order is something I do to the customer. I'm passing an Order object to the Customer object and expecting it to do something with it. That might be simply creating a reference, or there might be a ton of business logic that goes along with it. Either way, the Customer Object knows what to do with the order object. Then, I pass the customer to the service to save the data. All that service does is takes the customer and saves it down. It couldn't care less about the addition of the order.

The second suggests something very different. The second assumes that the service is where all the business logic goes because it's being passed these two objects that know nothing about each other and it is expected to know what to do with them.

Which is right depends on your circumstances, but my guess is the first. The second makes the interaction of the two objects dependent on the service and that seems very limiting to me. But maybe there's some reason in your application that you want that.

Related Topic