Wednesday, July 17, 2019

Effective Java Study Note - Avoid creating unnecessary objects


  1. Reuse is faster, an object can always be reused when it's immutable. For example, use String abc = "abc" instead of String abc = new String("abc"), the later would unnecessarily create an object.
  2. Or the static factory method is preferred, for example, use Boolean.valueOf("true") instead of new Boolean("true").
  3. Avoid repeated creating objects, for example, use Pattern.compile("xxx") instead of String.match("xxx") because String.match would internally create a new Pattern object.
  4. Avoid use boxed primitive type repeated when you can use primitive type directly.

Effective Java Study Note - Prefer dependency injection to handwriting resources

Dependency injection is equally applicable to constructors, static factory methods and builder. It's useful when you need to pass an object to the constructor of the class or a class depends on one or more underlying resources whose behavior affects that of the class, greatly improves flexibility, reusability and testability.

Effective Java Study Note - Enforce noninstantiability with a private constructor

Sometimes you need to have a class has only static fields and static methods, like java.lang.Math. For this kind of class, add a private constructor to avoid instantiating by mistake.

Effective Java Study Note - Enforce the singleton property with a private constructor or an enum type

There are 2 common ways to implement singleton, one is to provide a public static factory method, the other one is to have a public final field. There is also an approach to provide singleton: A single value enum(preferred approach).

Tuesday, July 16, 2019

Effective Java Study Note - Consider a builder when faced with many constructor parameters

Builder helps increasing the readability of constructing a new object. Use a builder when the number of parameters of a constructor is more than 4, if it's less than 4, it may not worthy to use builder because it takes extra memory space and time to construct an object.

Monday, July 15, 2019

Effective Java Study Note - Consider static factory methods instead of constructors

There are advantages of static factory methods, you can have name for the method, to make its usage more clear; or you can hide the implementation; you don't even create a new instance when the method invoked. There're many common names used for the static factory methods as mentioned below.

  • from
    • Date.from(instance)
  • of
    • EnumSet.of(A, B, C)
  • valueOf
    • Integer.valueOf(100)
  • instance
  • getInstance
  • create
  • newInstance
  • getType
    • FileStore fileStore = Files.getFileStore(path)
  • newType
    • BufferedReader bufferedReader = Files.newBufferedReader(path)
  • type
    • Collections.list(data)