How to check if there is any null attribute in the object?

2

I have a Person class and I want to check if there is any null attribute, either because I can not save a person with null attribute. I want to avoid a lot of if . Is there any way to do this?

public void salvar(Pessoa p) throws Exception {

    if (p.getNome() == null) {
        throw new Exception("Nome nulo");
    } else if (p.getIdade == null) {
        throw new Exception("Idade nula");
    } else if (p.getCorDosOlhos == null) {
        throw new Exception("CorDosOlhos nulo");
    }
}
    
asked by anonymous 30.03.2016 / 18:07

1 answer

4

As I said the ramaral in comments, if you need all data to have some value, ideally, the guy guarantees this by himself. It can be via constructor and setter methods (making validations or having their absence) in addition to automatic initialization of the members.

If this is not possible, if it depends on context, that is, time can have null members, time can not, have you ever thought that you have two problems and maybe two different types? One of them allows the null and the other does not allow. So at one point you can use one to create the other, and obviously that which does not allow nulls will fail if it is not properly initialized.

Does not that solve it? Okay. You've already found the most obvious solution. And if you want to throw specific exceptions for each member that fails, there are no simple solutions.

If you can have a general solution for any member that fails, you can use reflection . With this technique you can scan all members in a generic way and check the values. It is not very performative but solves in most cases. If you have different (exceptional) cases you will have to deal with all this.

If you need performance you can use a code generator to parse the class and create a code that checks all members one by one directly without writing the code for each class. Obviously it will be necessary to run a tool to generate the new code every time someone fiddles with the class (this can be automated too, of course).

It's still possible to automate the process a bit, even though you have different treatments for each member. This will require a framework or a more complex code generation tool. In any case, members will need notes or some other way to tell what to do with each member.

Everything will depend on convention to automate better.

With such a generic question it is difficult to give a more specific solution.

Reflection example:

for (Field field : Pessoa.class.getDeclaredFields()) {
    if (Modifier.isPrivate(field.getModifiers())) {
        //faz alguma coisa aqui com field
    }
}

Documentation .

Tutorial .

Question in SO about the subject. Another .

I'm not a fan of the term attribute, I prefer field .

    
30.03.2016 / 18:47