Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

  • Avoid that the user calls the factory with a non-treated carName.

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?

like image 917
Mik378 Avatar asked Oct 09 '11 11:10

Mik378


3 Answers

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.

like image 148
GaryF Avatar answered Sep 27 '22 21:09

GaryF


Neither. Use an Enum and make the method an instance method of the Enum itself. No if's required.

like image 21
user207421 Avatar answered Sep 27 '22 21:09

user207421


I would use Enums; I don't like Strings used in this case. The advantage with enums is that you could switch over them (which will not work with strings) and you don't need to handle false input.

like image 26
MasterCassim Avatar answered Sep 27 '22 21:09

MasterCassim