#310 VisibilityModifier: fields used in an inner class

open
nobody
None
5
2012-10-10
2004-08-03
Gunter Blache
No

Do not complain about a protected modifier that should be private,
if the field is used in an inner class.
This is because the access from an inner class to a private field is
emulated via synthetic accessor methods that have a negative
impact on performance.

Discussion

  • Lars Kühne
    Lars Kühne
    2004-08-04

    Logged In: YES
    user_id=401384

    This is a feature request, not a bug (Checkstyle works as
    advertized) - moving this issue to RFE tracker.

    How should we handle non-private, non-anonymous inner classes?

    class Outer {
    public class Inner {
    protected int field = 0;
    }
    private Inner inner = new Inner();
    private int x = inner.field; // access field to trigger
    rule you suggest
    }

    The problem here is that classes living in the same package
    as Outer can also access Inner.field. Should we really dump
    encapsulation in favour of performance here?

    Do you have any data that backs your performance claim? I
    always thought that trivial accessor methods would be
    inlined by hotspot...

     
  • Gunter Blache
    Gunter Blache
    2004-08-05

    Logged In: YES
    user_id=1095933

    In fact I meant it the other way around:

    class Outer {
    protected int x;
    class Inner {
    private void m() {
    System.out.println(x);
    }
    }
    }

    In this case VisibilityModifier complains that x should be
    private.

    On the topic of the perfomance issue: this is mainly a
    warning that I have enabled in Eclipse, and I intend to
    trust it. I did not do measurements myself. But this warning
    is helpful in detecting a broken encapsulation, and I would
    not like to trade it off for no false positive messages from
    Checkstyle ( because the errors from VisibilityModifier are
    helpful as well )