The question of where to define constants in Java has repeatedly appeared on the forums, but I'm struggling to solve a problem that makes me comfortable.
To make it simple, suppose I have two classes: WriteMyData and ReadMyData . None of them are subclasses of the other. Both classes have two constants that are vital to their work: String DELIMITER and int LENGTH . In the future, I might want to change the meaning of these constants so that they are defined somewhere suitable.
Consensus often favors the enum type. However, in my case, there is nothing to list, so in the end I have only one element in enum , which I call DEFAULT :
public enum DataSettings { DEFAULT(",", 32); private final String delimiter; private final int length; DataSettings(String delmiter, int length) { this.delimiter = delimiter; this.length = length; } public String getDelimiter() { return delimiter; } public int getLength() { return length; } }
Thus, in both my classes, I access the constants through DataSettings.DEFAULT.getDelimiter() and DataSettings.DEFAULT.getLength() .
Is this a really good OO style? Is enum overkill possible? If I do not use enum , what should I do instead? Creating an interface for constants seems to be underestimated, and there seems to be no natural superclass for my classes. Is a beginner's error having only one default element in enum ?
java enums constants
Dustbyte
source share