《Effective Java》Chapter 4
Chapter 4: Classes and InterfacesItem 12: Minimize the accessibility of classes and members
The rule of thumb is that you should make each class or member as inaccessible as possible.
For members (fields, methods, nested classes, and nested interfaces) there are four possible access levels, listed here in order of increasing accessibility:
? private— The member is accessible only inside the top-level class where it is declared.
? package-private— The member is accessible from any class in the package where it is declared. Technically known as default access, this is the access level you get if no access modifier is specified.
? protected— The member is accessible from subclasses of the class where it is declared (subject to a few restrictions [JLS, 6.6.2]) and from any class in the package where it is declared.
? public— The member is accessible from anywhere.
It is nearly always wrong to have public static final array field.





The public array should be replaced by a private array and a public immutable list:






Alternatively, if you require compile-time type safety and are willing to tolerate a performance loss, you can replace the public array field with a public method that returns a copy of a private array:









Item 13: Favor immutability
The Java platform libraries contain many immutable classes, including String, the primitive wrapper classes, and BigInteger and BigDecimal.
a) Don't provide any methods that modify the object (known as mutators).
b) Ensure that no methods may be overridden.
c) Make all fields final.
d) Make all fields private.
e) Ensure exclusive access to any mutable components.
Immutable objects are inherently thread-safe; they require no synchronization.
The only real disadvantage of immutable classes is that they require a separate object for each distinct value.
This approach works fine if you can accurately predict which complex multistage operations clients will want to perform on your immutable class. If not, then your best bet is to provide a public mutable companion class. The main example of this approach in the Java platform libraries is the String class, whose mutable companion is StringBuffer.
Item 14: Favor composition over inheritance
Unlike method invocation, inheritance breaks encapsulation.












































This class looks reasonable, but it doesn't work. Suppose we create an instance and add three elements using the addAll method:




Internally, HashSet's addAll method is implemented on top of its add method, although HashSet, quite reasonably, does not document this implementation detail.
Here's a replacement for InstrumentedHashSet that uses the composition/forwarding approach:























































































































Inheritance is appropriate only in circumstances where the subclass really is a subtype of the superclass. In other words, a class B should extend a class only A if an “is-a” relationship exists between the two classes.
Item 15: Design and document for inheritance or else prohibit it
The class must document precisely the effects of overriding any method.
Constructors must not invoke overridable methods, directly or indirectly.















Here's a subclass that overrides m, which is erroneously invoked by Super's sole constructor:

























It prints out null the first time because the method m is invoked by the constructor Super() before the constructor Sub() has
a chance to initialize the date field.
If you do decide to implement Cloneable or Serializable in a class designed for inheritance, you should be aware that because the clone and readObject methods behave a lot like constructors, a similar restriction applies: Neither clone nor readObject may invoke an overridable method, directly or indirectly.
Item 16: Prefer interfaces to abstract classes
Existing classes can be easily retrofitted to implement a new interface.
Interfaces are ideal for defining mixins. (eg. Comparable)
Interfaces allow the construction of nonhierarchical type frameworks.
Interfaces enable safe, powerful functionality enhancements via the wrapper class idiom.
Using abstract classes to define types that permit multiple implementations has one great advantage over using interfaces: It is far easier to evolve an abstract class than it is to evolve an interface.
Item 17: Use interfaces only to define types
When a class implements an interface, the interface serves as a type that can be used to refer to instances of the class.
The constant interface pattern is a poor use of interface, use constant utility class instead. (public static final fileds)
Item 18: Favor static member classes over nonstatic
There are four kinds of nested classes: static member classes, nonstatic member classes, anonymous classes, and local classes. All but the first kind are known as inner classes.
One common use of a nonstatic member class is to define an Adapter that allows an instance of the outer class to be viewed as an instance of some unrelated class. It is possible, although rare, to establish the association manually using the expression enclosingInstance.new MemberClass(args).




















If you declare a member class that does not require access to an enclosing instance, remember to put the static modifier in the declaration. If you omit the static modifier, each instance will contain an extraneous reference to the enclosing object. Maintaining this reference costs time and space with no corresponding benefits.
One common use of a static member class is as a public auxiliary class, useful only in conjunction with its outer class.









































































One common use of an anonymous class is to create a function object, such as a Comparator instance. Another common use of an anonymous class is to create a process object, such as a Thread, Runnable, or TimerTask instance.










Local classes are probably the least frequently used of the four kinds of nested classes. A local class may be declared anywhere that a local variable may be declared and obeys the same scoping rules.
posted on 2005-12-18 00:24 Scott@JAVA 閱讀(523) 評論(0) 編輯 收藏 所屬分類: Effective Java