AnOldSoul
AnOldSoul

Reputation: 4207

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

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

    }

Upvotes: 1

Views: 922

Answers (2)

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) { 

Upvotes: 0

G. Ann - SonarSource Team
G. Ann - SonarSource Team

Reputation: 22804

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())

Upvotes: 4

Related Questions