Item 13: Minimize the accessibility of classes and members

Data hiding and encapsulation is one of the building blocks of a great design. Well minimizing the accessibility seems to be a pretty obvious thing. Well, although it is, its benefits are worth mentioning.

  1. Decoupled Modules – Since the exposed APIs of a module will be limited.
  2. The code becomes maintainable. Well you’ve got the hint from the point 1.
  3. It takes the understanding and the correct application of the Access Control Mechanism of Java.

Rules of Thumb

  1. Make each class or member as inaccessible as possible.
  2. If a method overrides a super class method, it is not permitted to have a lower access level in the subclass than it does in the super class.e.g. Inheritance – C1#method1 -> C2#method1 -> C3#method1
    here, if access modifier of method1 in C1 is protected, then method1 in C2 and C3 cannot be private, it can be protected or public.
  3. Final fields, even though referring to an immutable object must be kept private. Because, keeping it public may cost you flexibility to switch it to a new internal data representation.
  4. Never expose access to final static array field. As the clients may try to update the content. This is a security flaw.
    // Potential security hole!
    public static final Thing[] VALUES = { ... };

    This can be easily fixed as –

    private static final Thing[] PRIVATE_VALUES = { ... };
    public static final Thing[] values() {
        return PRIVATE_VALUES.clone();

    One could also use Arrays.copyOf instead.

I think Joshua Bloch has made himself very clear here, ” Minimize the accessibility of classes and members”. Savvy?

Well, feel free to ask doubts, if any.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: