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?– Piovezan