Validating null and/or empty fields when creating Java objects

Asked

Viewed 962 times

1

I have an object and would like to force the filling of attributes at the time of the creation of the object. What is the best way to do this?

There are the annotations @NotNull, @NotEmpty and @NotBlank Hibernate, but it doesn’t fit the set here. I am currently using a method to validate before the object is used in another class, below is an example:

import java.util.Objects;

public class User {

    private String usuario;
    private String senha;

    public User(String usuario, String senha) {
        this.usuario = usuario;
        this.senha = senha;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public boolean validate() {
        return (Objects.nonNull(usuario) && Objects.nonNull(senha)) && (!usuario.isEmpty() && !senha.isEmpty());
    }
}

For example, this validation can be done in the constructor and in the methods set thus avoiding a method to validate?

  • I read over it, but this.usuario = Objects.requireNonNull(usuario); I wouldn’t take your call?

2 answers

2


I am even in doubt if the doubt is that same, because it seemed to me simple too (if that is it I complete the answer, otherwise I erase):

class Main {
  public static void main(String[] args) {
    User usuario = new User("joao", "123");
    System.out.println(usuario);
  }
}

class User {
    private String usuario;
    private String senha;

    public User(String usuario, String senha) {
        setUsuario(usuario);
        setSenha(senha);
    }
    public String getUsuario() { return usuario; }
    public void setUsuario(String usuario) {
        if (usuario == null || usuario.isEmpty()) throw new IllegalArgumentException("usuário esstá inválido");
        this.usuario = usuario;
    }
    public String getSenha() { return senha; }
    public void setSenha(String senha) {
        if (usuario == null || usuario.isEmpty()) throw new IllegalArgumentException("usuário esstá inválido");
        this.senha = senha;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I think it’s bad to make an exception to this, but it’s the way it’s usually done in Java (I’ve seen some Java programmers do it differently, so there’s hope, but I doubt it’ll become the standard).

  • out of curiosity, why do you think this approach bad?

  • I believe that making an exception or not will depend on your business rule. If it is a crucial data where without it the system does not work, for example, it makes sense to throw an exception.

  • @nullptr look up everything I say about exception on the site. In answer to both, exception should not be a business rule, exception is something exceptional, if it is something that you know is normal to happen is no exception. This code does not let you create the object if it is invalid, have you tested it? I have tested: https://repl.it/@Maniero/Validationspecific.

  • @Maniero, in this case I would find it interesting to mention another validation format as an option. I wonder why I have seen several implementations using this method, and several others not using it (using services for validation, generating other problems as the devs forget to call to validate), using validation by libs (Hibernate-Validator for example). I see that all approaches have pros and cons and I’m even seeking to put together an article with comparatives on, since they can all happen at different times within an application.

  • @nullptr not in this question that does not ask for it, but one of my most voted answers speaks of alternative methods

1

I’m also not a fan of playing exception, as spoken by @Maniero, as this will be released at runtime and would make no difference regarding null verification.

Instead of making an exception, use import org.springframework.lang.NonNull; @NonNull variable. This will show the developer that there is a possibility of creating an object with variable null.

inserir a descrição da imagem aqui

Lombok import lombok.NonNull; also have note for this (never tested).

Anyway, you have options to do the validation ( @Maniero reply) without launching exception.

https://www.baeldung.com/spring-null-safety-annotations

https://www.baeldung.com/java-avoid-null-check

Browser other questions tagged

You are not signed in. Login or sign up in order to post.