When you have a list of fixed values I tend to define an enumeration for it:
public class Person {
public final Gender gender;
public Person(Gender gender) {
this.gender = gender;
}
}
public enum Gender {
MALE("male"),
FEMALE("female");
private final String value;
Gender(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
But I have also seen something like this, where the enumeration values are implemented as static final fields.
public class Person {
public static final String MALE = "male";
public static final String FEMALE = "female";
public final String gender;
public Person(String gender) {
// Check argument
this.gender = gender;
}
}
I have seen that Swing classes often use the second approach. For example when you call JFrame#setDefaultCloseOperation
you can pass an integer value as argument or use one of the static members of the JFrame
class.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Wouldn't it be better to define an enumerations for those actions because it would be impossible to pass just any integer as argument to the method. Besides that some constants seem to be duplicated as there is WindowConstants.DISPOSE_ON_CLOSE
which you can use too. With enumerations it is clear what you have to pass as an argument. What would be a reason to use this approach and avoid enumerations?