SonarQube failing to recognize ObjectUtils.isEmpty()

  • Operating system: Windows 11
  • SonarQube for IntelliJ plugin version: 10.22.0.81244
  • IntelliJ version: IntelliJ IDEA 2024.3.5
  • Programming language you’re coding in: Java
  • Is connected mode used: No

SonarQube is incorrectly recognizing a rule java:S2259 in my code, because it does not know that ObjectUtils.isEmpty(mockObject) checks whether the ‘mockObject’ is null. It thinks that mockObject could still be null, even after the ObjectUtils.isEmpty check.

Hi,

Welcome to the community!

Could we get a reproducer code sample where the rule is wrongly raising an issue?

 
Thx,
Ann

Hi G Ann,

Please excuse me, I sent the wrong documentation link. It’s the isEmpty() method from here: Apache Commons Lang 3.11 API

I’m still working on getting a code snippet for you; I’m having trouble reproducing the issue in a test class. I’ll get back to you on Monday.

Thanks,
Daniel

1 Like

Good morning G Ann,

I’ve narrowed down the problem. To my understanding, SonarQube only raises this rule incorrectly for a “Nullable” function’s return value. Here’s a code snippet:

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.lang.Nullable;

import java.util.HashMap;
import java.util.Map;

public class IsEmptyNullCheck {

    private final TestCache cache;

    public IsEmptyNullCheck() {
        this.cache = new TestCache();
    }

    public void codeSnippet() {
        String a = cache.get("a");
        if (ObjectUtils.isEmpty(a)) {
            System.out.println("a is empty or null");
        } else {
            System.out.println("a is " + a.toUpperCase()); // Issue incorrectly raised at this line
        }
    }

    static class TestCache {
        private final Map<String, String> map;

        TestCache() {
            this.map = new HashMap<>();
            this.map.put("a", "b");
        }

        // Issue only arises with this annotation
        @Nullable 
        public String get(String key) {
            return map.get(key);
        }
    }
}

Thank you for your attention and patience.
Daniel

Hi Daniel,

Thanks for the reproducer! I’ve flagged this for the language experts.

 
:slight_smile:
Ann

1 Like

Hi there, indeed we do not track the behavior of this ObjectUtil class.
I created this ticket to keep track of the issue.

Thanks for the report!

1 Like