Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SONAR complaining to change the condition so that it does not always evaluate to "false"

public String generateURLSafeToken(String username, char[] password) throws CredentialTokenException {
    this.tokenValid = false;

    String token = null;
    if ((username.length() < 1) || (username == null)) {
        throw new CredentialTokenException("Username cannot be an empty string or null.");
    }
    if ((password.length < 1) || (password == null)) {
        throw new CredentialTokenException("Password cannot be an empty or null.");
    }

I am facing this error in line 4 and line 7 (username == null and password == null)

And I need this part in my code. I am trying isEmpty() instead of null but facing problems in that also . What is an alternate way or the solution to fix this SONAR error

like image 300
Aawan Avatar asked Sep 14 '16 13:09

Aawan


1 Answers

The conditions which always evaluates to false are username == null and password == null.

Let's take the example of username. The operator || is short-circuiting meaning it won't evaluate the right hand side if the left hand side is true. Basically, there are 2 cases:

  • The username given is not null. The condition username.length() < 1 is evaluated
    • If the result is true, we return directly and enter the if branch
    • If the result is false, we try to evaluate username == null. But since the username given is not null, this always evaluate to false.
  • The username given is null. The condition username.length() < 1 is evaluated. This actually stops right there: it will throw a NullPointerException and will not evaluate the right hand side.

Therefore, you can see that whenever the username == null condition was actually evaluated, the result was always false. This is what the SonarQube warning is telling you.

The solution here is to reverse your 2 conditions. Consider having

if (username == null || username.length() < 1)

instead. If you start over and go through each case, you'll notice that none of the expressions will always have the same result:

  • The username given is not null. First condition clearly evaluates to false and the second is evaluated, which may return true or false.
  • The username given is null. The first condition clearly evaluated to true and short-circuits.
like image 188
Tunaki Avatar answered Nov 04 '22 00:11

Tunaki