We have an object that needs to be converted to a different type before storing it in database. For that purpose, the library provides an annotation over the field that specifies the appropriate class[given as ClassName.class] to use for converting back & forth.
The class implements an interface of the library that has the marshall & unmarshall methods.
public class ObjectConverter implements Marshaller<Instant> {
public static final ObjectConverter CONVERTER = new ObjectConverter();
@Override
public String marshall(Instant obj) {
return obj.toString();
}
@Override
public Instant unmarshall(Class<Instant> clazz, String obj) {
return Instant.parse(obj);
}
}
Now, we need to manually convert Instant
to appropriate type at certain places. A straight-forward approach would be to create a new instance everywhere and invoke those public methods.
My colleague was suggesting to have a static final
field of itself and use it wherever needed in order to avoid creating it each and every time. But, my argument was that nobody is stopping from creating a new instance, thus defeating the purpose of the static instance.
A better way to handle this, in case object creation is really costly would be to have a utility class that has static methods for converting back & forth. These can be invoked in both the marshaller and during manual conversions. Is there any better approach?
Is it a good practice to have both static instance and public constructor at the same time?