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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s