The question of where to define constants in Java has appeared numerous times in forums, yet I am struggling to settle on a solution I feel comfortable with.
To make it simple, suppose I have two classes: WriteMyData
and ReadMyData
. None is a subclass of the other. Both classes share two constants that are vital for their operation: String DELIMITER
and int LENGTH
. In the future I might want to change the value of these constants so they should be defined somewhere appropriate.
The consensus seems to often favour the enum
type. However, there is nothing to enumerate in my case, so I end up with only one item in my 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 really good OO style? Is the use of enum
perhaps overkill? If I do not use enum
, what should I do instead? Creating an interface for constants seems to be frowned upon, and there seems to be no natural superclass for my classes to derive from. Is it a beginners mistake to have only one default item in an enum
?