Search code examples
javaspringoopdesign-patternsfactory-pattern

If the factory pattern forces you to use default constructors then how should one design the class interface requiring parameterized constructors?


I have a set of DAOs (Data access objects) that need to be fetched from a DAOFactory (using the factory-method pattern).

Now we have the case that DAOs must always be initialized with parameters e.g.: (with String params)

MyDataDAO myDAO = new myDAO("myProject", "myProjectWallName");

Now, having a bunch of DAOs has required us to refactor (using the factory pattern) and here are the conflicting forces:

  1. If we refactor our DAOs to NOT use any default arguments (probably a good thing) we may land up having setters/getters for the mandatory members that MUST be initialized. Implying probably null checks/assertions littered all throughout (bad thing IMO)
  2. The other way is to force every method of the DAO to carry the corresponding mandatory arguments along with what they already have (too much data/long parameter list - probably bad but maybe the only choice?)
  3. Use Spring! Well we do for some of the purely stateless DAOs which really don't require any defaults to be set up. But I don't think Spring really supports run-time constructor-parameter initialization, since it creates and caches the objects at start-up. So back to square one (Spring may support this but I really haven't been able to find anything about this as yet. Help? :)

So how should one go about designing a 'good' interface for the classes that are to be instantiated using a factory i.e., best practices to follow in this regard. I've always encountered the non-parameterized constructor case up until now where I do feel a valid need/reason for having the parameters. I personally feel it's bad OO to have a default constructor only and set everything through setters-getters, defeating the very purpose constructors exist to solve!

Confused...


Solution

  • A Factory pattern is used to create an object and make sure that it is in a valid state when it's returned to the caller.

    If your object has required properties, returning it with a default constructor and not initialized properties, won't return a valid state to the caller. In such a case, everywhere you call the factory, the code should also know which fields are required and initialize them after the factory call. That way you duplicate initialize code (and knowledge) and the whole idea of the factory pattern is to remove such duplication.

    So required fields should be passed as parameters to a factory method.