본문 바로가기

Study/Effective Java

Effective Java - Chapter2 Summary (1)

반응형

2. Creating and Destroying Objects

  • when and how to create objects
  • how to ensure they are destroyed in a timely manner
  • how to manage any cleanup action that must precede their destruction
  1. Consider static factory methods instead of constructors 

    public static Boolean valueOf(boolean b){ 
    	return b? Boolean.TRUE : Boolean.FALSE; 
    }
    1. A static factory method is not the same as the Factory Method Pattern from Design Patterns

    2. Providing static factory methods has both advantages and disadvantages.

    <Advantages>

    1. Static factory methods have names - a static factory with a well0chosen name is easier to use and the resulting client code easier to read
    2. Static factory methods are not required to create a new object each time they're invoked
    3. They can return an object of any subtype of their return type
    4. The class of the returned objects can vary from call to call as a function of the input parameters.
    5. The class of the returned objects need not exist when the class containing the method is written.

    <Disadvantages>

    1. Classes without public or protected constructors cannot be subclassed
    2. They are hard for programmers to find.
      1. Common names for static factory methods
        • from
        • of
        • valueOf
        • instance or getInstance
        • create or newInstance
        • getType
        • newType
        • type
  2. Consider a builder when faced with many constructor parameters

    1. Telescoping constructor pattern → It is hard to write client code when there are many parameters, and harder still to read it.
    2. JavaBeans Pattern → allows inconsistency, mandates mutability / this pattern precludes the possibility of making a class immutable and requires added effort on the part of the programmer to ensure thread safety.
    3. Builder Pattern → well suited to class hierarchies. the safety of telescoping constructor pattern + the readability of the JavaBeans pattern / you must first create its builder → it could be a problem in performance-critical situations.
  3. Enforce the singleton property with a private constructor or an enum type

    1. Making a class a singleton can make it difficult to test its clients → it's impossible to substitute a mock implementation for a singleton useless it implements an interface that serves as its type.
    2. the public field approach(preferable) - the API makes it clear that the class is a singleton - the public static filed is final, So it will always contain the same object reference.
    3. The static factory approach - it gives you the flexibility to change your mind about whether the class is a singleton without changing its API. a method reference can be used as a supplier
    4. A single-element enum type is often the best way to implement a singleton
반응형