Consider static factory methods instead of constructor

The advantages of static factory method

  • Unlike constructor, static factory methods have name
  • Not required to create a new object each time they’ve invoked
  • They can return an object of any sub type of their return type
  • The class of the object returned by a static factory method need not even exist at the time the class containing the method is written. Such flexible static factory methods form the basis of service provider frameworks, such as the Java Database Connectivity API (JDBC).

The Disadvantage

  • The main disadvantage of providing only static factory methods is that
    classes without public or protected constructors cannot be subclassed.
  • Factory methods are not readily distinguishable from other static methods. You can avoid this by drawing attention to static factories in classes or interface comment, Some common names for factory methods are valueOf, of, getInstance, newInstance, getType, newType
  public static Boolean valueOf(boolean b) {
     return b ? Boolean.TRUE : Boolean.FALSE;
  }

factory method of Boolean

Leave a comment