I have an application with an entity of class A. A has a field B, which is used by some viewmodels but not all. The field B is loaded in a separate loading operation from a different source.
What layer should be responsible for loading this field B? I see three alternatives:
- Implement logic in A to load B whenever it’s accessed. It works, but requires some logic in the A class. I feel that the entity classes should have minimal logic, and certainly not have logic related to loading data from the data source (but I may be wrong).
- Let the data access layer (DAL) load B whenever it loads an instance of A. This is not optimal as loading data from the datasource (which is a remote server) is slow, and only a few of the instances of A requires the field B.
- Let the viewmodel load B using the DAL if it needs it. This seems to me (a guy relatively unexperienced in the ways of MVVM) to be the most “MVVM-y” way of doing this.
#3 seems less “elegant” compared to #1 when it comes to the “it just works”-factor (with #1, accessing the field B would automatically load it from the datasource). But #3 seems to separate the concerns in a better way, as the entity objects is not given the responsibility of loading more data.
Go for #3.
Entity models, which in a case of a client app should be data transfer object, should not have any logic at all. This will (most probably) save a lot of time when you will try to write unit tests or/and chage the dto’s.
I would simply inject a dependency into each view model representing master item, and then allow it to get it data. This will also allow to rather simply notify user with a busy indicator thorugh IsBusy property on the item view model.
You can also imlement a separate Command class which will handle download task, but it will require some upper level services to notify user with in process operation, but this is the cleanest aproach I can imagine.
So start with 3, and if logic to download child will grow reasonably enough to incapsulate it in a command class, just do it. But try to avoid static implamantations by all costs.
Sorry for a bad grammar.