Given an application that involves, say, Companies, I might have a Company class. I will have a data access layer that populates a List <Company>. However, there will be times (such as displaying a search result) where I only need to display the Company name, telephone and postcode properties, and it seems to me that populating the entire Company object with all its properties seems wasteful.
What would be the right way to go about this in terms of a DDD design? Would I create View specific classes, such as a CompanySearchResult object which only exposes the properties I'm interested in displaying?
That sounds like a reasonable approach to me.
Later on, if the customer comes to you asking for your SearchResult
to display something unrelated to the Company
model - something crazy like the number of nearby ice cream shops you'll have a much easier time appending this to your CompanySearchResult
than your domain object.
This is what is typically known as a "view model" or a Data Transfer Object. You may not want your view to have access to the entire data tree exposed by your domain model. Especially if exposing your domain model means that your view will have to dig deep into your object graph to pull the data it needs, a View Model can make alot of sense to simplify working with the model objects. In your case, if you are simply pulling direct properties off of the model object, it would make sense if you want to hide the extraneous data not needed by the rest of your domain model.
The approach you suggest can quickly increase the number of DAO:s you need to create and become a maintenance nightmare. The approach that several ORMs take is to proxy the data access, so your data access layer will return a list of interfaces, and the database call will be postponed until you invoke the data accessor, for instance
list.getCompany(1).getName()
. This is call lazy loading. You will still need to make a trade off between making many small or fewer big queries. This type of tasks is one of the strengths of ORMs, you can usually ask your ORM to prefetch parts of the object graph which you think will be used, and leave out other parts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With