【问题标题】:How can the below line generate sonar qube issue of always evaluating to false?下面的行如何产生总是评估为假的声纳 qube 问题?
【发布时间】:2016-07-18 09:35:09
【问题描述】:

我有以下代码行,sonarqube 说,

“更改此条件,使其不会总是评估为假”

下面是线。

if (params.isEmpty() && params == null) {
        throw new ServiceSDKException("Parameters cannot be empty or null!");
    }

以下是整个方法,以备不时之需。

public void init(String params) throws ServiceSDKException {
        if (params.isEmpty() && params == null) {
            throw new ServiceSDKException("Parameters cannot be empty or null!");
        }
        String[] configParams = params.split(",");
        options.setMqttURL(configParams[0]);
        options.setMqttClientID(configParams[1]);
        try {
            options.setWillMessage("v1/items/mqtt/0/event/will"
                    , "Last will"
                    , 2, true);
            new File("./db").mkdir();
            edgeNode = EdgeNodeFactory.createMQTTChannel("./db", options,
                    subscriptionTask, 500, 500);
            isClientConnected = true;
        } catch (EdgeNodeException e) {
            isClientConnected = false;
            throw new ServiceSDKException("EdgeNodeException occurred", e);
        }

    }

【问题讨论】:

  • 如果 params 为 null,您将收到 NullPointerException。您应该首先检查 null ,然后使用 or 操作( || )检查 isEmpty()
  • 什么都不是""null。因此,条件永远无法评估为真。

标签: java null sonarqube conditional sonarqube-5.0


【解决方案1】:

这个条件:

if (params.isEmpty() && params == null) { 

将您带到一个死代码,因为它们永远不可能同时为真。

这就是 sonarqube 抱怨的原因。

为什么:

String#isEmpty() 是一个方法,如果 String 不是 null 引用,则返回一个布尔值

快速修复:

更改逻辑测试:

 if (params.isEmpty() || params == null) { 

【讨论】:

    【解决方案2】:
    if (params.isEmpty() && params == null)
    

    如果您已成功执行params.isEmpty 而不抛出NullPointerException,那么params 必然是非空的。

    我想也许你的意思是:

    if (params == null || params.isEmpty())
    

    【讨论】:

      猜你喜欢
      • 2017-06-12
      • 2013-11-23
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 2016-11-25
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多