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!
– Jônatas Dourado Porto
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
@Maniero I added the link in the reply, thank you!
– hkotsubo