I have a project where ViewModels are nested within each other such that they essentially are a string-typed replication of the domain hierarchy. For example, if our domain has the following relationships:
Organization has 1 to many Environments
Environment has 1 to many Machines
then there will be an OrganizationViewModel that has one to many EnvironmentViewModels in it, and the EnvironmentViewModel will have one to many MachineViewModels themselves. This style of hierarchy is then reused throughout the app, with one of about five ViewModels of this type. (e.g. EnvironmentViewModel is used for multiple pages, MachineViewModel for many of them as well, depending on the level of the hierachy being viewed...I've simplified this for purposes of discussion but the hierachy is a little larger than just the 3 above).
Now, as much as I'd like to come down from above and condemn this practice, I haven't been able to find much information on this. Can anyone point me to more details about established practice? Anecdotes to share?
(My own bias is that these ViewModels shouldn't be nested within each other this way, and the ViewModels should actually correspond to the Views, not the domain objects. I find it pretty messy with some maintainability issues. But I'd like to know what others think or have experienced.)
I've attached this question for reference but it describes nesting a domain object within a viewmodel, not viewmodels within each other.
The viewmodel should be as flat as possible (although nested immutable objects used to logically group multiple related properties are ok for tidying purposes).
Dont think of it as "the viewmodel should correspond to the view", think of it the other way around: "the view is an html representation of the viewmodel data".
ViewModel
is a horrible term because its not a view and its not a model, its a representation of a resource.
If I do:
`GET /User/1`
I expect back some data representing User 1. If thats in HTML format because i sent
`Accept: text/html`
then so be it. Consider what your viewmodel would look like as XML or JSON.
Try and avoid nesting viewmodels as youre creating a dependency chain, just duplicate the properties, youre not violating DRY really
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