Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
Final field marked @NotNull is not initialized

I have this code:

public static class MyWebDriver extends RemoteWebDriver {
    @NotNull
    private final String nodeId;

    public MyRemoteWebDriver(@NotNull String nodeId) {
        super();
        this.nodeId = nodeId;
    }

    @Override
    public void quit() {
        System.out.println("deleting node: " + nodeId);
    }
}

and it's guaranteed that nodeId that is passed into constructor is not null. And because nodeId field is final I expect it to be initialised in my quit() method.

But, in super() constructor there is a try-catch block which in case of exception calls quit() method and throws an exception. And in this case nodeId that I get in my quit() method is not initialised (has null value).

Are there any ways of avoiding it except

@Override
public void quit() {
    if (nodeId != null) {
        System.out.println("deleting node: " + nodeId);
    }
}

this one? Which looks pretty stupid, because nodeId is marked as @NotNull.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

But, in super() constructor there is a try-catch block which in case of exception calls quit()

This are two problems in one:

  1. constructors should not do any work except storing the given parameters in (final) member variables.

    [edit]

    Does that mean classes should not validate their inputs? I know many people who would disagree with having all of their objects possibly invalid instead of never existing at all. – chris

    By "should not do any work" I mean constructor should not calculate any property value from the parameters or call a dependency or a non public method to do the check.

  2. constructors should never call any other than private and/or final methods (within the class), either directly or indirectly (i.e. you mustn't call a final method which in turn invokes a non-final method).


The reason why you run into this problem is the violation of the single responsibility Pattern and Separation of Concerns.

What ever you do in the super classes constructor should most likely be done in a separate class and only the results of that process should be passed into your class (and its super class).

This obviously means that the quit() method also belongs to a different class.

about 4 years ago · Santiago Trujillo Relatório

0

This is of course easily explained by the fact how Java works. An object of type MyWebDriver is not initialized, including its fields, i.e. including in your case nodeId until its fields inherited from the super class are initialized, i.e., in your case, until super() returns.

So if an exception in super is thrown, clearly nodeId will be null.

I don't think there's any solution (except some similar to what you're suggesting) unless the framework you're using (which you didn't specify) provides some workaround.

about 4 years ago · Santiago Trujillo Relatório

0

You can move initialization logic from super constructor to protected init() method and invoke it after nodeId initialization.

Maybe clearer design can be used here but it's hard to suggest anything without full example.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda