BMC to acquire Netreo. Read theBlog

Cleaner Code with Static Factory Methods

By: Alexandra
  |  May 2, 2023
Cleaner Code with Static Factory Methods

A classic creational design pattern from the gang of four is the factory method pattern. Examples of this pattern typically involve a factory class that constructs objects of a different type. The objects that are created are usually implementations of an interface. This pattern provides a layer between consumption (the caller) and creation (the factory). An additional benefit is that the factory provides named methods to the consumer. This can be especially useful depending on the parameters required to construct the object.

An offshoot of this pattern is to provide static factory methods in the class you want an instance of. A static factory method is a public static method on the object that returns a new instance of the object. These type of methods share the same benefits as the traditional factory method design pattern. This is especially useful for value objects that don’t have a separate interface and implementation class.

Static factory methods example

To demonstrate the benefits of static factory methods, let’s jump into an example. Which of these time span objects represent 5 seconds?

newtimespan Static Factory Methods

Not as easy as it sounds unfortunately. This problem is made worse because these constructors take multiple integers. Hours, minutes, seconds, milliseconds. Days? Ticks?

 

Let’s refactor the example to use the static factory methods that already exist in the TimeSpan class.

timespanfrom Static Factory Methods

 

It is pretty obvious now which time span objects represent 5 seconds. No code comments or IntelliSense needed.

The key elements to implement this pattern are simple: the factory method must be public, static, and return an instance of the class in which it is defined. If, like TimeSpan, you will have many factory method variants on your class, it’s helpful to name them similarly (“FromX”) but distinctly, to avoid the kind of ambiguity that we see in TimeSpan’s constructor overloads.

 

Eric Martin Principal Engineer / Stackify

 

 

 

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]