Table of Contents

Effective Java

By Joshua Bloch

Chapter 1 Introduction

…

Chapter 2 Creating and Destroying Objects

Item 1: Consider static factory methods instead of contructors

Advantages of static factory methods over constructors:

  1. static methods have names
  2. static methods must not create a new object (example: Boolean.valueOf(boolean))
    • instance-controlled classes
  3. static methods can return instances of any subtype of their return type
    • possibility to hide subtypes from public → inteface-based frameworks
  4. class of the returned object can vary from call to call as a function of the input parameters
  5. class of the returned object need not exist when the class containing the method is written
    • service provider frameworks
      • → dependency injection (default implementation: java.util.ServiceLoader)

Limitations/Shortcomings of static factory methods:

  1. the main limitation of providing only static factory methods is that classes without public or protected constructors cannot be subclassed
  2. hard for programmers to find
    • to “fix” it use common names like
      • from - makes object from one parameter, e.g. Date.from(instant)
      • of - makes “aggregated” object, e.g. Set<Rank> faceCards = EnumSet.of(JACK, QUEEN, KING);
      • valueOf - more verbose alternative to from and of
      • instance or getInstance - returns maybe not new instance
      • create or newInstance - returns new instance
      • getType - like getInstance but is in a different class
      • newType - like createInstance but is in a different class
      • type - concise alternative to getType and newType, e.g. Collections.list()

Item 2: Consider a builder when faced with many contructor parameters

Problem: many fields where some of them are not always necessary.

Solution: Builder pattern

NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();

Disadvantages of Builder:

Item 3: Enforce the singleton property with a private constructor or an enum type

…

Item 11: Always override hashCode when you override equals

…