问题描述
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 == null
和password == 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 notnull
. The conditionusername.length() < 1
is evaluated- If the result is
true
, we return directly and enter theif
branch - If the result is
false
, we try to evaluateusername == null
. But since theusername
given is notnull
, this always evaluate tofalse
.
因此,您可以看到,只要实际计算
username == null
条件,结果始终为false
.这就是SonarQube警告告诉您的内容.Therefore, you can see that whenever the
username == null
condition was actually evaluated, the result was alwaysfalse
. 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
,第二个条件的值为,可能返回true
或false
. - 给出的
username
是null
.第一个条件明确评估为true
和短路.
- The
username
given is notnull
. First condition clearly evaluates tofalse
and the second is evaluated, which may returntrue
orfalse
. - The
username
given isnull
. The first condition clearly evaluated totrue
and short-circuits.
这篇关于SONAR抱怨改变了条件,因此它并不总是评估为"false".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- If the result is
- 如果结果为