Factory Class for ViewModels – Is It Necessary?

asp.net-mvcdesign

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

  • Instances of B contains or compositely aggregates instances of A
  • Instances of B record instances of A
  • Instances of B closely use instances of A
  • Instances of B have the initializing information for instances of A and pass it on creation.

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.

  • DRY - If two or more controllers need to share the viewmodel construction behaviour, encapsulating it in a distinct component would facilitate code re-use and avoid duplication.
  • If the construction behaviour has dependencies on other system components such as repositories, validators etc, and you don't want to introduce this coupling to the controller itself (in GRASP terms, a pure fabrication).

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!