A colleague of mine suggested using a factory class for creating viewmodel objects in our ASP.NET MVC solutions. The idea being that it can help with the design, and maintainability, of the way viewmodels are built in our apps.
I wanted to find out if anyone else has experience of this. I've done some research and found very little on this practise.
Currently we create viewmodel objects at the controller level eg
public ActionResult Index()
{
return this.View(this.BuildIndexViewModel());
}
So this.BuildIndexViewModel() is responsible for creating the viewmodel class (obviously :). But we're looking into the possability of:
public ActionResult Index()
{
return this.View(ViewModelFactory.CreateIndexViewModel());
}
This is an interesting idea, but I'm not 100% convinced. I was interested in other people's opinions on this.
Best Answer
In this case I would say the best guidance to follow would be the GRASP principles. In particular look at the four criteria of assigning object creation:
In general, a class B should be responsible for creating instances of class A if one, or preferably more, of the following apply
Your controller class (B) matches the items #3 & #4 of that list (and #2 if the viewmodel is POSTed back) , so it's already a very sensible place for the viewmodel (A) construction behaviour to live. As I see it there would only be two reasons which would compel me to extract that construction behaviour into a specialist class.
Looking back at those 4 object creation criteria in GRASP, I would only extract the behaviour to a separate factory if it won me an extra tick on that list. Otherwise there wouldn't be any value in doing so.
Hope that helps!