How can the below line generate sonar qube issue of always evaluating to false?

914 views Asked by At

I have the below lines of code and sonarqube is saying,

"Change this condition so that it doesn't always evaluate to false"

.

Below is the line.

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

Below is the whole method in case you need.

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);
        }

    }
2

There are 2 answers

0
G. Ann - SonarSource Team On BEST ANSWER
if (params.isEmpty() && params == null)

If you've successfully executed params.isEmpty without throwing a NullPointerException, then params is necessarily non-null.

I think perhaps you meant:

if (params == null || params.isEmpty())
0
ΦXocę 웃 Пepeúpa ツ On

This condition:

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

is bringing you to a dead code since they can never be both true.

that is the reason why the sonarqube is complaining.

Why:

String#isEmpty() is a method that returns a boolean if the String is not null referenced

Quickfix:

Change the logical test for:

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