Search code examples
design-patternsdomain-driven-designfactory-pattern

Passing arguments in a factory pattern


I am learning Domain Driven Design and I am in the 'naively confident' phase right now. DDD(the blue book) speaks about having a factory pattern for building aggregates. I tried using it for my application and in one of the scenarios it just doesn't seem right and I dont know how to proceed. Below is my case:

class CompanyFactory {
    public Company getCompany(Type type, Long numOfShares) {
        switch(type) {
            case PUBLIC:
                return new PublicCompany(numOfShares);
            case PRIVATE:
                return new PrivateCompany();
        }
}

Now the argument 'numOfShares' is relevant only for the PublicCompany. But when my type is 'PRIVATE', I still have to send the 'numOfShares' even though it wont be used.

I tried AbstractFactory but in that case each factory would create exactly one type of object and IMHO it misses the whole point of using a factory in the first place. Any pointers on how to do this will be great.


Solution

  • A factory is mostly useful to abstract away a complex creation process or to decouple the client code from concrete implementations where it makes sense.

    Here I suppose that you may have implemented a generic createCompany(String type, Map<String, String> info) application service method that is called from the presentation layer and so you must instantiate the right concrete company based on the type dynamically.

    While I agree that this use case would benefit from a factory, perhaps you could make the process more straight forward by defining explicit createPublicCompany and createPrivateCompany methods on the application service, leaving it to the presentation layer to call the right one. You would therefore push the decision making upwards, where it has to be made anyway in the first place (e.g. to show the right fields) and you wouldn't need a factory anymore.

    If that isin't practical for some reasons and you still need to dynamically choose the concrete implementation from a Type then your factory contract will have to be abstract enough to accomodate all company types.

    If you implemented a generic createCompany method at the application level then you already solved that problem before.