Several times now I come across a use case when I need to define an interface for how the classes themselves are created. One such example might be if I want to create an interface class that defines an interface with which objects can be serialized and non-serialized (entering data into a database sent as JSON, etc.). You could write something like this:
abstract class Serializable { String serialize(); Serializable unserialize(String serializedString); }
But now you have a problem, since serialize() is the proper instance method, and unserialize() should be the static method (which is not inherited or not used by the interface) or the constructor (which also isnโt inherited).
This leaves a state in which classes that implement the Serializable interface are needed to define the serialize() method, but there is no way to require these classes to define a static unserialize() constructor or a Foo.fromSerializedString() constructor.
If you create an instance method unserialize() , then the non-esterization of the Foo implementation class will look like this:
Foo foo = new Foo(); foo = foo.unserialize(serializedString);
which is rather bulky and ugly.
The only other option I can think of is to add a comment to the Serializable interface, which understands that implementation classes define the appropriate static method or constructor, but this is obviously error-prone if the developer skips it, and the code termination hurts.
So, is there a better way to do this? Is there some kind of template with which you can have an interface that forces the implementation of classes to determine how to create yourself or something that gives a general effect?
source share