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
:
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?
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.
Neither. Use an Enum and make the method an instance method of the Enum itself. No if's required.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With