vendredi 13 mai 2022

Inappropriate Intimacy in factory

My Factory has dependency on Repository. It calls many methods from Repository. Lets say something like this:

class CarFactory {
    private Repository repository;

    Car create() {
        detail = repository.findSomeDetail();
        if(detail.large()) {
          anotherDetail = repository.findAnotherDetail();
          return new Car(detail, anotherDetail);
        } else {
          anotherDetail = repository.findYetAnotherDetail();
          if(anotherDetail.expensive()) {
              cheapDetail = repository.findCheapDetail();
              return new SecondHandCar(cheapDetail);
          } else {
              smallDetail = repository.findSmallDetail();
              return new SmallCar(smallDetail);
          }
    }
}

It is hard to test, I need to mock lots of Repository methods. One problem is that Repository takes a lot of time to find something, so I can not find everything and then pick whatever I need. I need to call its methods only after certain criteria was met. Repository manages only single entity type, so I don't think it is a God Object. I tried to use Builder and ended up with:

class CarFactory {
    private Repository repository;
    private CarBuilder builder;

    Car create() {
        detail = repository.findSomeDetail();
        return builder.buildBasedOn(detail);
    }
}

However, it introduces new dependency in CarFactory and there is still problems inside Builder itself.

Aucun commentaire:

Enregistrer un commentaire