Skip to main content
6 of 6
added 162 characters in body
TheCatWhisperer
  • 5.3k
  • 1
  • 23
  • 43

Does only a create method classify a class as a factory?

In my current project, I find my self making factories, but for two very distinct reasons:

Reason #1: To assist my IoC container if a particular class needs an parameter that is only known when the class is created. This might also include reading data from a config. This kind of factory contains no business logic, only initialization logic.

Reason #2: The creation of an entity needs complex validation logic, and I want to keep this logic out of my constructor so it stays simple. This kind of factory is only about business logic around the creation of a new entity.

Furthermore, when I create a factory for reason #2, I find myself tempted to put deletion logic there as well, as the deletion of the entity is often complex and beyond the scope of the entity being deleted; however, one would be hard pressed to call a class with a deletion method a factory.

Reason #1 Example:

class WidgetRepositoryFactory
{
    IUserRepository Create(userType)
    {
         int configValue = int.Parse(Config.get("ConfigValue"));
         IUserRepository repo = userType == "user1" : new User1Repo(configValue) : new User2Repo(configValue);
         return repo;
    }
}

Reason #2 Example:

class WidgetFactory
{
     Result<Widget> Create(var1, var2)
     {
          Result r = new Result();
          if (var1 < 0)
          {
              r.AddError("var1 too low!");
              return r;
          }

          if (var1 > var2)
          {
              r.AddError("var1 too high!");
              return r;
          }

          r.Obj = new Widget(var1, var2);
          r.Success = true;
          return r;
     }
}

When I create a factory for reason #2, is it really correct to call it a factory? Is there a better term for this kind of class? Is there preexisting terminology to describe these two very distinct cases?

TheCatWhisperer
  • 5.3k
  • 1
  • 23
  • 43