因此它并不总是评估为

因此它并不总是评估为

本文介绍了SONAR抱怨改变了条件,因此它并不总是评估为"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.");
    }

我的代码中需要这一部分.我正在尝试isEmpty()而不是null,但也遇到了问题.有什么替代方法或解决此SONAR错误的解决方案

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

推荐答案

始终评估为false的条件是username == nullpassword == null.

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

让我们以username为例.运算符||短路,表示它不会评估右手如果左侧为true,则为.基本上有2种情况:

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:

  • 给出的username不是null.条件username.length() < 1被求值
    • 如果结果为true,我们将直接返回并进入if分支
    • 如果结果为false,我们尝试评估username == null.但是由于给出的username不是null,因此该始终的值为false.
    • 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.

      因此,您可以看到,只要实际计算username == null条件,结果始终为false.这就是SonarQube警告告诉您的内容.

      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.

      这里的解决方案是颠倒您的2个条件.考虑拥有

      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:

      • 给出的username不是null.显然第一个条件的值为false,第二个条件的值为,可能返回truefalse.
      • 给出的usernamenull.第一个条件明确评估为true和短路.
      • 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.

      这篇关于SONAR抱怨改变了条件,因此它并不总是评估为"false".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:27