Table of Contents
Create and destroy objects
Methods Common to All Objects
Classes and Interfaces
Minimize the accessibility of classes and members
Minimize mutability
Immutable class
Composition over inheritance
Create and destroy objects
Static factory methods instead of constructors
Builder when faced with many constructor parameters
Singleton with private constructor or enum type
Enforce noninstantiability with private constructor
Avoid creating unnecessary objects
Eliminate obsolete object references
Avoid finalizers
Methods Common to All Objects
Classes and Interfaces
Minimize the accessibility of classes and members
Information hiding / encapsulation for decoupling: Modules only communicate through APIs, implementation details are hidden
Rule: Make each class / member as inaccessible as possible.
Package-private: part of implementation, not
API
.
If pp class only used by one class ⇒ private nested class
Protected/Public: Support forever
Private and package private members still can leak into
API
if class implements Serializable
“Acceptable” to make private member package-private to test it (but not further)
public static final fields FIELD_NAME only should contain immutable or primitive objects, no array
clone array / unmodifiableList for private static array accessors
In public classes, use accessor methods, not public fields
Minimize mutability
Immutable class
No methods that modify object's state
Final class (not extensible)
Final fields
Private fields
Exclusive access to mutable components
Composition over inheritance