TIL — Static Factory Methods

Today my work tasks led me to read about static factory methods, which are a different approach to initializing Java classes.



Bottles moving through an actual factory.
Photo by Waldemar Brandt on Unsplash
Effective Java (Addison-Wesley 2018) helped me understand this concept, and here is my brief take on that reading:

  • Static factory methods are given names, which helps us as developers better and more quickly understand what they do.
  • They save time and memory in your program, because they aren’t required to create new instances when they are run.
  • They can create subtypes that differ from release to release. These subtypes don’t even have to have their class written at the time that the method is written.
They certainly don’t solve every problem. They don’t scale well with growing parameters. But the example given in the book illustrates this concepts use:
public static Boolean valueOf(boolean b) {
       return b ? Boolean.TRUE : Boolean.FALSE;
}
Here you dynamically return an initialized boolean with concise and easy-to-understand code. That is just simply worth it.
Cheers.

Comments