How to handle Null records? In the bank or app? (java & mysql)

2

I'm integrating a legacy (MySQL) database with a new module (Java - this problem-giving object is a bean) that I'm developing.

I have a method that does a select and returns some results that possibly have some null data and this generates an exception Java.lang.NullPointerException .

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

    
asked by anonymous 25.04.2018 / 22:28

1 answer

5

Hello,

About your questions:

  

I treat this in the database, generating empty values for these records

I would not do this, unless it makes sense in the business context of the application. Eventually it will make sense for one or another field, but not for everyone. The data is the ones and your application needs to deal with them, so the problem will continue.

  

Or do I deal with this in my code, kind of ignoring these exceptions?

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

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

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

Make:

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

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

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

And to use Optional :

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

So it is very clear to the following code that name is optional and the concept of something null , from this point on, is no longer a concern.

    
25.04.2018 / 22:36