Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing a Domain Object from multiple DTOs

Suppose you have the canonical Customer domain object. You have three different screens on which Customer is displayed: External Admin, Internal Admin, and Update Account.

Suppose further that each screen displays only a subset of all of the data contained in the Customer object.

The problem is: when the UI passes data back from each screen (e.g. through a DTO), it contains only that subset of a full Customer domain object. So when you send that DTO to the Customer Factory to re-create the Customer object, you have only part of the Customer.

Then you send this Customer to your Customer Repository to save it, and a bunch of data will get wiped out because it isn't there. Tragedy ensues.

So the question is: how would you deal with this problem?

Some of my ideas:

  • include an argument to the Repository indicating which part of the Customer to update, and ignore others

  • when you load the Customer, keep it in static memory, or in the session, or wherever, and then when you receive one of the DTOs from the UI, update only the parts relevant to the DTO

IMO, both of these are kludges. Are there any other better ideas?

@chadmyers: Here is the problem.

Entity has properties A, B, C, and D.

DTO #1 contains properties for B and C.

DTO #2 contains properties for C and D.

UI asks for DTO #1, you load entity from the repository, convert it into DTO #1, filling in only B and C, and give it to the UI.

Now UI updates B and sends the DTO back. You recreate the entity and it has only B and C filled in because that is all that is contained in the DTO.

Now you want to save the entity, which has only B and C filled in, with A and D null/blank. The repository has no way of knowing if it should update A and D in persistence as blanks, or whether it should ignore them.

like image 565
moffdub Avatar asked Jan 24 '23 01:01

moffdub


1 Answers

I would use factory to load a complete customer object from repository upon receipt of DTO. After that you can update only those fields that were specified in DTO.

That also allows you to apply some optimistic concurrency on your customer by checking last-updated timestamp, for example.

like image 159
Damir Zekić Avatar answered Mar 16 '23 09:03

Damir Zekić