質問

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?

役に立ちましたか?

解決

When creating or deleting an entity, where the logic for both is non trivial, the code validating the conditions has more to do with a Use Case and should go in the layer of your application where use cases are handled.

For architectures similar to Onion Architecture, this would be the service layer.

他のヒント

I find myself tempted to put deletion logic there as well

This is a sign that you should put validation logic into an initialize method; then you can control the deletion logic as well.

When I create a factory for reason #2, ...

Reason #2 may point else where; I think that this extra logic from reason #2 needs to be moved either into the class as another member or moved somewhere else, For example if you are reading a config, the validation may belong there.

is it really correct to call it a factory?

In your example I might call it a SpecialWidgetFactory; assuming this code doesn't belong in the caller.

ライセンス: CC-BY-SA帰属
所属していません softwareengineering.stackexchange
scroll top