BugsOverflow
BugsOverflow

Reputation: 538

SonarLint "Replace this if-then-else statement by a single return statement"

Im not being able to fix this code smell:

public static boolean esStringVacio(final Object valor) {
        if (valor == null) {
            return true;
        }
        String valorTrim = valor.toString().trim();
        if ((valorTrim).equals("")) {
            return true;
        }
        if ((valorTrim).equals("null")) {
            return true;
        }
        return false;
    }

Tried like so but code smell persist:

if (valor == null || valor.toString().trim().equals("") || valor.toString().trim().equals("null")) {
        return true;
    } else {
        return false;
    }

Upvotes: 1

Views: 4144

Answers (3)

Philippe
Philippe

Reputation: 29

In my opinion, the answers before fail to actually explain the question of the code smell. So the code smell is because you use a condition to either return true or false anyway.

If you change your code of

if (valor == null || valor.toString().trim().equals("") || valor.toString().trim().equals("null")) {
    return true;
} else {
    return false;
}

to

return (valor == null || valor.toString().trim().equals("") || valor.toString().trim().equals("null"))

The smell is gone. But double check that the returned true or false is as expected.

Upvotes: 0

Amir
Amir

Reputation: 134

You can shorten it to:

return (valor == null || valor.toString().trim().equals("") || valor.toString().trim().equals("null"));

Edit : You can shorten even more to:

return ((String.valueOf(valor).trim().equals("null")) || (StringUtils.isBlank(valor)) ;

Thanks to Ernest for suggesting this.

Upvotes: 4

EpicPandaForce
EpicPandaForce

Reputation: 81549

You can combine the last 3 returns into a single OR, and it'd still be reliable / readable.

public static boolean esStringVacio(final Object valor) {
    if (valor == null) {
        return true;
    }
    String valorTrim = valor.toString().trim();
    return valorTrim.equals("") || valorTrim.equals("null");
}

Upvotes: 2

Related Questions