How to handle Null records? In the database or app? (java & Mysql)

Asked

Viewed 1,245 times

2

I am integrating a legacy database (Mysql) with a new module (Java - this problem object is a bean) that I am developing.

I have a method that makes a select and returns some results that eventually has some data null and this generates an Exception Java.lang.NullPointerException.

So far so good, I understand this problem, but my question is: do I treat it in the bank, generating empty values for these records, or do I treat it in my code, like ignoring these exceptions? And if you ignore them in the code, how do I do it?

  • 1

    In the application because this is a programming error. Unless it should not have the null in the database, and in many cases should not even.

1 answer

5


Hello,

About your doubts:

I treat it in the bank, generating empty values for these records

It wouldn’t do that unless it makes sense in the business context of the application. Eventually it will make sense for one or the other field, but not for everyone. The data are those and your application needs to deal with them, so the problem will continue.

or I treat it in my code, like ignoring those exceptions?

You’ll deal with it in the code but do not ignore Exceptions. The less you get involved with exceptions, the better your code will look to me. What you need to do is map which fields can come null and prepare your application for this.

For example, if a column nome can come null, instead of doing something like:

try {
    nomeEmMaiusculo = nome.toUppercase();
} catch (NullPointerException ex) {
    //ignorar, nome está null
}

Do:

if (nome != null) {
    nomeEmMaiusculo = nome.toUppercase();
}

If you are using Java 8, you can improve this code using Optional. So, when you receive the name that can be null, you immediately treat it as optional:

Optional<String> optNome = Optional.ofNullable(nome);

And to use the Optional:

if (optNome.isPresent()) {
    nomeEmMaiusculo = optNome.get().toUppercase();
}

So it’s pretty clear to the next code which name is optional and the concept of something null, from this point on, it ceases to be a concern.

  • 1

    Pelamor, what an excellent answer!!! Clap!!! Thank you very much Dherik, clarified right here.

Browser other questions tagged

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