Today I saw the following JavaFX related code in a project:
issueComboBox.setConverter(new IntegerStringConverter());
yearComboBox.setConverter(new IntegerStringConverter());
and thought: Do I really need to create two instances of IntegerStringConverter?
IntegerStringConverter has the following code:
public class IntegerStringConverter extends StringConverter<Integer> {
@Override public Integer fromString(String value) {
if (value == null) {
return null;
}
value = value.trim();
if (value.length() < 1) {
return null;
}
return Integer.valueOf(value);
}
@Override public String toString(Integer value) {
if (value == null) {
return "";
}
return (Integer.toString(((Integer)value).intValue()));
}
}
So I don't need two instances, because there is no state in IntegerStringConverter, also not in StringConverter. If I could rewrite the class I would rewrite it as a singleton, like that:
public final class IntegerStringConverter extends StringConverter<Integer> {
public static final IntegerStringConverter INSTANCE = new IntegerStringConverter();
private IntegerStringConverter() { }
@Override public Integer fromString(String value) {
if (value == null) {
return null;
}
value = value.trim();
if (value.length() < 1) {
return null;
}
return Integer.valueOf(value);
}
@Override public String toString(Integer value) {
if (value == null) {
return "";
}
return (Integer.toString(((Integer)value).intValue()));
}
}
So users of this class can't create multiple instances:
issueComboBox.setConverter(IntegerStringConverter.INSTANCE);
yearComboBox.setConverter(IntegerStringConverter.INSTANCE);
Its a class from javafx.util.converter package. I think it isn't implemented in the way i suggested because the JavaFX developers want to give us the possibility to extend this class.
The point of the matter is, is it nearly always a good idea to implement classes ( which are not pure helper classes with only static methods) with no state as singletons to prevent multiple instantiations for memory and performance reasons?