Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Static Factory Pattern vs. Named Constructor Idiom vs. Named Constructor. Wait, What?

DZone's Guide to

Static Factory Pattern vs. Named Constructor Idiom vs. Named Constructor. Wait, What?

Get a glimpse of the naming, the history, the limitations, and the uses of the classic object construction process, and the available solution of using static methods.

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

There are several ways to construct an object instance. The most common way is to use, of course, a ‘new’ keyword. However, as with anything else, both theory and practice have decided to make this more complicated, and invent new fancy terms for it.

The GoF are not authors of the “static factory pattern,” however, it is one of the most famous and simple construction patterns in any object-oriented programming language, and it is used in PHP.

Definition of Constructor

The constructor is a special method of a class that can be invoked by using either a “new” keyword (new Object()) in the process of object instantiation, or by using reflective voodoo, which depends on the support of the programming language that is being used (however, reflections are, usually, an edge case, irrelevant, and out of the scope of this article).

Constructors can produce ONLY two results of its invocation:

  • A pointer to a new instance of the class that is being constructed.
  • An exception.

Practical Problems With the Object Construction Process

There are certain problems that may occur when it comes to constructing an object when we use class constructors.

Constructors Do Not Expose Intent

We know that constructors will construct the object, but we can not know how it's going to do that. In the majority of scenarios, that is not an issue. However, in certain use cases, that can be somewhat important. Consider this example:

class Person
{

}

class Client
{
    const REGULAR = 'regular';
    const VIP = 'vip';

    private $person;
    private $type;

    public function __construct(Person $person)
    {
        $this->type = self::REGULAR;
        $this->person = $person;
    }
}


Pay attention to the Client class and its constructor. From the implementation details, we know that it will construct a “regular” client. However, if we do not inspect it, we cannot know that (unless we are provided with proper documentation).

By using a static factory pattern, we can explain the intent of the object construction process:

class Client
{
    const REGULAR = 'regular';
    const VIP = 'vip';

    private $person;
    private $type;

    private function __construct(Person $person, $type)
    {
        $this->type = $type;
        $this->person = $person;
    }

    public static function createVipClient(Person $person)
    {
        return new static($person, self::VIP);
    }

    public static function createRegularClient(Person $person)
    {
        return new static($person, self::REGULAR);
    }
}


Constructors Will Always Create a New Instance of its Class 

Well, that is its purpose, right?

It is, but sometimes you need to have only one instance of some class, or you want to have several named instances, or it is just too expensive to construct a new instance, so you will try to reuse already created, unused instances first, etc.

You have to prevent uncontrolled object instantiation, so constructors would have to have a “private” access modifier. So, the only reasonable implementation method of constructor would be a static factory pattern (you can use reflections as well, but that is arguable in this case).

Constructor Will (Really) Always Create a New Instance of its Class

Again, that is its purpose, right?

However, in some languages, like Java, it is possible to have a private class, or make it visible only within the scope of the package (library). By implementing the static factory pattern, it is possible to create and return instances of any other class.

For example, in some scenarios, the implementation that should be used can be determined only at runtime, where it is required to inspect execution environment, or, based on provided parameters, a certain class instance would be constructed and provided. Of course, all possible instances that can be provided by the implementation of the static factory pattern should implement some predetermined interface, so all of this could make sense.

This possibility is very useful in languages that support it.

When it comes to PHP, the usefulness of this possibility is very limited, and it is constrained to anonymous classes.

Some Languages Don’t Support Constructors/Method Overloading in the Traditional Sense

Languages like PHP do not allow the possibility of overloading constructors/methods like in Java, C#, etc. Something similar can be achieved with "func_get_args()," but that approach is arguable. Therefore, it is deliberately stated that "PHP does not support constructors/methods overloading in the traditional sense."

Implementing the static factory pattern can provide us with the solution for constructor overloading — that is, multiple constructors.

A side note: In a talk I held (slide 42, footnote) on Nov. 15, 2016, organized by PHP Serbia, I stated that overcoming a lack of language support is not a design pattern. However, I have to admit that I have doubts about this particular use case, and I have not found (yet) a point of view by "higher minds." So for now, I will admit that that statement is arguable, and it is quite possible that I was wrong.

The Origins

I couldn’t find the origin of "static factory pattern," nor the name of the author of the pattern. Neither I could find the author of “nNamed constructor idiom.” However, I am pretty sure that C++ is the inventor, and the concept was stolen by Java, renamed for marketing purposes in the “very beginning of time” — while rest joined the party afterward and used the term with the word “pattern” in it — because patterns are cool.

Of course, the PHP community decided not to use either of the original names, but to mutilate one of them. And that is how we have a “named constructor” term — as if there is not enough names for the same thing.

What Do I Call it, Then?

Named constructor” is the wrong name for sure. It is not a constructor because it violates the very definition of constructors — constructors can return only an instance of its class or throw an exception. There is no third option — whatever you do, you can get only those two results. Static methods, on the other hand, can produce every imaginable result, so that name is not suitable either way.

However, “named constructor idiom” is quite suitable — the word “idiom” does make a difference.

But personally, I prefer “static factory pattern." It explains the intent, gives a hint on how to implement it, and by having “pattern” in the name, it explains that it is a recipe for solving some common development problems.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:
constructor ,static factory ,named constructor ,design patterns ,java

Published at DZone with permission of Nikola Svitlica, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}