programming_languages:java:effectivejava

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

  • 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
  • No methods that modify object's state
  • Final class (not extensible)
  • Final fields
  • Private fields
  • Exclusive access to mutable components
  • programming_languages/java/effectivejava.txt
  • Last modified: 2017/02/19 14:46
  • by phreazer