[Java:S2039] Don't complain about private inner classes

The rule wants me to declare visibility explicitly. That’s very fine. I support that.

But in the following case it is wrong.

public class A
{
    private static class B
    {
        int i; // FP
    }
    
    private void test()
    {
        B b = new B();
        int i = b.i;
    }
}

For private inner classes (not necessarily static) the no-modifier is not only handy, but exactly correct. Private would work, but no-modifier officially allows me to access from outside the (inner) class.

Also for closures this should be ignored, even if in this case it’s better to declare private.

public Supplier< Integer > foo()
{
    return new Supplier<>()
    {
        int counter = 0; // FP
        
        @Override
        public Integer get()
        {
            return ++counter;
        }
    };
}

Hello, I was updating the status of this rule and stumbled into this old thread. For the record:

The rule wants me to declare visibility explicitly. That’s very fine. I support that.

In fact, I don’t think it’s fine. This rule is too naive, it reports any field without “public”, “private” or “protected” modifier. However, “no modifier” has a special meaning in Java (package protected), that can not be represented thanks to a modifier. Even if the use of this visibility is rather rare, we end up raising an issue for every legitimate usage.

The problems you are reporting are perfect examples, they are legitimate use cases.

We were considering deprecating this rule for quite some time, I don’t see any reason why we should not move forward at this point: SONARJAVA-4018.

Best,
Quentin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.