javaenumsdesign-patternsfactorystatic-factory

Use Enum or String for a static factory method?


Is it better to use enum or String to dispatch to the right object to create in a static factory method ?

Example with String :

public static Car createCar(String carName){
    if(carName.equals("Ferrari")){
        return new Ferrari();
    }
    else if(carName.equals("Porsche")){
        return new Porsche();
    }
    ....
}

Example with enum :

public static Car createCar(CarEnum carEnum){
    if(CarEnum.FERRARI.equals(carEnum)){
        return new Ferrari();
    }
    else if(CarEnum.PORSCHE.equals(carEnum)){
        return new Porsche();
    }
    ....
}

For now, according to me :

Benefit of using enum :

Drawback of using Enum :

Increase dependencies because a change into enum (FERRARI becoming ENZO_FERRARI for instance) will require modification on client. However, with String we could redirect Ferrari to Enzo Ferrari instance without recompile client code. Of course, we could make the same thing for client using old enum values with a redirection of FERRARI to ENZO-FERRARI enum but for me it implies that enum would have to keep old values to make client compatible... no make sense for me.

I would like to know what are your opinions on this subject?


Solution

  • If, as you do in this case, you have a fixed number of acceptable arguments to a method, then it's best to enforce that constraint as best as you can on the clients of the method. In this case, accepting any old string would cause more failures than using an enum.

    However, you might also consider, in a limited case like this, using named factory methods for each type of car: like createFerrari(), createPorsche() etc.