How to validate data passed to a constructor?

Asked

Viewed 428 times

2

Is there a way to handle possible errors or validations by instantiating a class using the constructor? For example, this is my constructor:

public boolean ContaFisica(int agenciaConta, int numeroConta, int digitoConta, String tipoConta, String senha, String confirmacaoSenha) {
    if(! senha.equals(confirmacaoSenha)) {
        return false;
    }
    this.agenciaConta = agenciaConta;
    this.numeroConta = numeroConta;
    this.digitoConta = digitoConta;
    this.tipoConta = tipoConta;
    return true;
}

Notice that he gives a return false when the passwords don’t match. Already in my code to instantiate the class could look like this:

if(ContaFisica conta1 = new ContaFisica(2442, 8053, 5, "CP", "1234", "1234")) {
    //DEU CERTO
}

4 answers

8


You didn’t create a constructor. In fact you created a method that returns a boolean, and which happens to have the same class name. But when you do new ContaFisica(...), is calling the builder, not the method.

Constructors should not have the declared return type, as they already return an instance of the class itself. If you want to validate something in the constructor and only create the instance if all the data is valid, you can make an exception if some data is invalid:

public ContaFisica(int agenciaConta, int numeroConta, int digitoConta, String tipoConta, String senha, String confirmacaoSenha) {
    if (!senha.equals(confirmacaoSenha)) {
        throw new IllegalArgumentException("Senha deve ser igual a confirmação da senha");
    }
    this.agenciaConta = agenciaConta;
    this.numeroConta = numeroConta;
    this.digitoConta = digitoConta;
    this.tipoConta = tipoConta;
}

To know if you fell in the invalid case, just capture the exception with a try/catch:

try {
    ContaFisica conta = new ContaFisica(123, 456, 7, "tipo", "senha", "senhadiferente");
    // conta criada, fazer o que quiser com ela
    ....
} catch (IllegalArgumentException e) {
    System.out.println("Não foi possível criar a conta: " + e.getMessage());
}

The other answers suggest creating the account and then calling a method to validate whether the account has all the valid data, or creating another field indicating whether it is valid or not.

You have to evaluate whether it makes sense to create an account with invalid data - if you don’t (and I believe you don’t, but only having all the context and requirements of your system to know), or create the account, throw the exception before.

Read also:


About creating a method with the same class name: although it is possible, it’s not a good idea.

  • Go for this guy, good explanation!

  • 2

    There’s this one also that talks about validation before the https://answall.com/q/252765/101 There’s a lot of important information and the patterns that are used.

  • @Maniero I added the link in the reply, thank you!

0

Constructor cannot return anything beyond the class in question.

Example: new ContaFisica(bla, bla, bla); returns only the Object ContaFisica, so how could a return boolean?

It is for this fact that it is NOT necessary to put void or the return type in the constructor, as it is explicit that it is the Class Object. Ideally you create a method to make this check that you need.

Ex:

ContaFisica conta1 = new ContaFisica(2442, 8053, 5, "CP", "1234", "1234");
if(conta1.validar()) 
{
    //
}
  • got it! then I would create a method to check if in the constructor, all code was run successfully?!!

  • Could yes!!!.

  • I’m sad with my comment now, I just tried to help.

0

You could make an exception or create a new attribute this.valido = true | false, Beyond the Constructor can return nothing but a new object of the class. For example:

public boolean ContaFisica(int agenciaConta, int numeroConta, int digitoConta, String tipoConta, String senha, String confirmacaoSenha) {
    if(! senha.equals(confirmacaoSenha)) {
        throw new Exeption('Senhas não coincidem');
    }
    this.agenciaConta = agenciaConta;
    this.numeroConta = numeroConta;
    this.digitoConta = digitoConta;
    this.tipoConta = tipoConta;
    return true;
}

Or else:

public boolean ContaFisica(int agenciaConta, int numeroConta, int digitoConta, String tipoConta, String senha, String confirmacaoSenha) {
    if(! senha.equals(confirmacaoSenha)) {
        this.valida = false;
    }
    this.agenciaConta = agenciaConta;
    this.numeroConta = numeroConta;
    this.digitoConta = digitoConta;
    this.tipoConta = tipoConta;
    this.valida = true
}

0

Class constructors by definition have as return a new class instance. Once you define another type as a return, it becomes a class method, not a constructor. In your case, nothing prevents you from creating a common constructor by taking the values and setting the attributes of the class, and creating an accessory method that tells you whether the password and confirmation are equal.

As for example the class below:

class ClasseA {
    private Long atributoA;
    private Long atributoB;

    public ClasseA(Long atributoA, Long atributoB) {
        this.atributoA = atributoA;
        this.atributoB = atributoB;
    }

    public boolean atributoAIgualAtributoB() {
        return this.atributoA.equals(this.atributoB) ;
    }
}

Instantiating:

    final ClasseA classeA = new ClasseA(1L, 2L);

    if(classeA.atributoAIgualAtributoB()) {
        //DEU CERTO
    }

Where you can check that equality and treat it with an exception.

Browser other questions tagged

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