Item 13: Minimize the accessibility of classes and members

1.  A well-designed module hides all of its implementation details, cleanly separating its API from its implementation. Modules then communicate only through their APIs and are oblivious to each others’ inner workings. This concept, known as information hiding or encapsulation, is one of the fundamental tenets of software design.

 

2.  Information hiding decouples the modules that comprise a system, allowing them to be developed, tested, optimized, used, understood, and modified in isolation.

 

3.  Make each class or member as inaccessible as possible.

 

4.  For top-level (non-nested) classes and interfaces, there are only two possible access levels: package-private and public.

 

5.  If a package-private top-level class (or interface) is used by only one class, consider making the top-level class a private nested class of the sole class that uses it.


6.  For members (fields, methods, nested classes, and nested interfaces), there are four possible access levels, in order of increasing accessibility : private, package-private, protected, public.

 

7.  If a method overrides a superclass method, it is not permitted to have a lower access level in the subclass than it does in the superclass.

 

8.  It is acceptable to make a private member of a public class package-private in order to test it, but it is not acceptable to raise the accessibility any higher than that.

 

9.  Instance fields should never be public.

 

10.  Classes with public mutable fields are not thread-safe.

 

11.  You can expose constants via public static final fields, assuming the constants form an integral part of the abstraction provided by the class. By convention, such fields have names consisting of capital letters, with words separated by underscores. It is critical that these fields contain either primitive values or references to immutable objects.

 

12.    It is wrong for a class to have a public static final array field, or an accessor that returns such a field.

 

13.    You can make the array filed private and add a public immutable list:

private static final Thing[] PRIVATE_VALUES = { ... };
public static final List<Thing> VALUES =
Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

 

 

Alternatively, you can make the array field private and add a public method that returns a copy of a private array:

 

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

 

你可能感兴趣的:(Effective Java,Encapsulation,Accessibility)