Search code examples
javadesign-patternsfactory-pattern

The correct way of creating a Factory for creating domain objects


The following is the code from my service layer

@Override
    public Boolean saveTransportation(SaveTransportationCommand addServiceCommand)  {
        return getServiceAgreementDao().saveTransportation((List<Transportation>)ServiceAgreementFactory.get(addServiceCommand));
}

I am trying to create domain objects from Command object, can I do validations and set values from command in Factory, is my approach correct, Or should I user Factory for only creating objects.


Solution

  • Factory is used for creating objects. In my opinion, it is not a crime to do validations and setting values inside factory methods before creating objects. If you are too concerned about the Factory doing such things (If you want your factory loosely coupled), you can have a Validator interface and pass it as an argument to Factory. Inside get method, you first validate. If the validate returns true, instantiate the object or else throw Exception.

    public interface Validator {
       boolean validate(SaveTransportationCommand command);
    }
    

    Modify the ServiceAgreementFactory.get() to take in Validator also.

    public class ServiceAgreementFactory {
    
      List<Transportation> get(SaveTransportationCommand command, Validator validator) {
          if(!validator.validate(command)) {
            // throw Exception
          }
      }
    }