views:

80

answers:

3

Should factories persist entities they build? Or is that the job of the caller? Pseudo Example Incoming:

    public class OrderFactory
    {
      public Order Build()
      {
        var order = new Order();
        ....
        return order;
      }
    }

public class OrderController : Controller
{
    public OrderController(IRepository repository)
    {
       this.repository = repository;
    }

    public ActionResult MyAction()
    {
       var order = factory.Build();
       repository.Insert(order);
       ...
    }
}

or

public class OrderFactory
{
  public OrderFactory(IRepository repository)
  {
     this.repository = repository;
  }

  public Order Build()
  {
    var order = new Order();
    ...
    repository.Insert(order);
    return order;
   }
}

public class OrderController : Controller
{
  public ActionResult MyAction()
  {
     var order = factory.Build();
     ...
  }

}

Is there a recommended practice here?

+6  A: 

As a general rule the factory has only one responsibility: create an instance and return it. I would not mix in persistence. I would view it as the responsibility of another class. In this case, it would be the controller.

Tom Cabanski
I'm too slow :p
zincorp
+1  A: 

The Factory's main purpose is the creation of objects. Once that object has been created it's up to you to decide what you want to do with it.

The only case where this would be different is if there's also a requirement that only once instance of the created object should exist, in which case you'll have some kind of pseudo-factory-singleton hybrid pattern going on.

zincorp
+1  A: 

If you decide to use a factory for singleton objects, you will need to manage the persistence of the singleton object. Other than that, I can't see why you'd want to have factories manage persistence.

Actually, having factories manage persistence - with the exception of when singletons are involved - would lead to the very opposite of proper separation of concerns, which is the raison d'etre for using factories in the first place.

code4life