Posts

Showing posts from January, 2015

Effective Java - Notes - Chapter 2 - Creating and Destroying objects

1. Consider static factory methods instead of constructorsStatic factory methods are the methods which simply return an instance of the class.
public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; }

Advantages:

a. They have names

Static factory methods have names, constructors do not. So it becomes easier for the user to know the purpose of these methods.

b. Objects can be cached

Unlike constructors, static factory methods can return the same objects (e.g. See Boolean class example above), which is memory efficient.

c. Static factory methods can return the subtype of their class type

With the same interface, which is a good practice.

d. They reduce the verbosity of creating parameterized instances,

Example,
Map<String, Boolean> map = new HashMap<String, Boolean>();versusMap<String, Boolean> map = Hashmap.newInstance(); Though after Java 1.7, this problem has been solved, you can use <> directly, e.g.,Map<String, Boolean> map = n…