I was wondering if there are cases where calling public or, in this case and particularly, protected methods in the constructor of an abstract class would be ok, or at least forgivable, given an adequate documentation of the intentions of the method.
My actual question concerns an abstract class IdentifiedConnection
that looks like this:
public abstract class IdentifiedConnection extends Connection {
private UUID uuid;
public IdentifiedConnection(String serverAddress, int port) throws IOException {
super(serverAddress, port);
this.uuid = this.aquireIdentifier();
}
public UUID getIdentifier() {
return this.uuid;
}
protected abstract UUID aquireIdentifier() throws IOException;
}
My intention is to get a UUID identifier from the server. If the server responds with a valid UUID, we set that UUID in the field of this class (named uuid
). If the server responds with a non-UUID message, we assume that the server is unreachable for some reason and throw an IOException
.
Generally I understand that calling an overridable method from the constructor is bad, since it leaves the class prone to various more or less hard-to-detect bugs. However, in this case I feel like doing this isn't actually too bad (as long as I javadoc the hell out of it).
What's your thoughts? Is this still a really bad idea? What alternative way of doing this do you suggest if you think this is bad?
I have left the code for the Connection
class out of this question as I think it's irrelevant.
I would recommend you to use a factory method in this case.
Write a static method called something like
This allows for better control of the creation and avoids the potential problems with leaking references to uninitialized objects.
Another approach would be to take a
Supplier<UUID>
as argument to the constructor, as follows:and in a subclass use it as