Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[java] UseCollectionIsEmpty should infer local variable type from method invocation #3858

Closed
MetaBF opened this issue Mar 18, 2022 · 1 comment
Labels
a:false-negative PMD doesn't flag a problematic piece of code in:type-resolution Affects the type resolution code
Milestone

Comments

@MetaBF
Copy link

MetaBF commented Mar 18, 2022

Affects PMD Version: 6.43.0

Rule: UseCollectionIsEmpty
https://pmd.github.io/latest/pmd_rules_java_bestpractices.html#usecollectionisempty

Description:
Please have a look at the following example, variable list is a local variable declared with type var, assigned by a method invocation getList(). The 'real' type of list should be inffered as java.util.List<String>, an implementation of interface java.util.Collection. Thus it's a good manner to use !list.isEmpty() instead of list.size() > 0 at line 8 (at point 1).

Code Sample demonstrating the issue:

import java.util.ArrayList;
import java.util.List;

public class Example {

    public void func() { 
        var list = getList(); 
        if (list.size()>0) { // point 1:  false negative
            System.out.println("!list.isEmpty() is better!");
            // ...
        }
    }

    private List<String> getList() { // mock
        return new ArrayList<>(); 
    }
}

Expected outcome:

PMD should report a violation at line 8 (at point 1), but doesn't. This is a false-negative.

Running PMD through: [CLI]

@MetaBF MetaBF added the a:false-negative PMD doesn't flag a problematic piece of code label Mar 18, 2022
@oowekyala oowekyala added in:type-resolution Affects the type resolution code needs-backport labels Mar 18, 2022
@jsotuyod
Copy link
Member

This is fixed in PMD 7.0.0-rc1. It won't be backported to PMD 6.

@oowekyala oowekyala added this to the 7.0.0 milestone Apr 24, 2023
adangel added a commit that referenced this issue Apr 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
a:false-negative PMD doesn't flag a problematic piece of code in:type-resolution Affects the type resolution code
Projects
None yet
Development

No branches or pull requests

3 participants