Static Factories vs Public Constructors
Normally, creating an instance of a class is done by calling new, which calls the constructor. Static factory provides a static method that returns an instance of the class. So, you are using static factory instead of the constructor. Providing a static factory method instead of a public constructor has both advantages and disadvantages.
Advantages of static factories over constructors:
- Static factory instances have names but constructors do not.
- Static factories can have two methods named differently but taking the same number and type of parameters.
- Subclassing isn’t possible but inheritance isn’t always the best way to reuse code.
Disadvantages of static factories over constructors:
- Can’t be subclassed.
- Poor naming conventions can make it hard to know what’s going on.
Dagfinn Reiersøl wrote an interesting post about this:
I’ve never considered visibility restrictions important enough to be a major argument against those languages that have lacked them (PHP 4). So why would I be sceptical of public constructors? I got the idea after reading Joshua Kerievsky’s book Refactoring to Patterns. One of his refactorings is called Replace Constructors with Creation Methods. In Java, unlike PHP, you can have multiple constructors that are distinguished only by the number and type of arguments. That may be practical sometimes, but as Kerievsky’s example shows, it be more readable to have creation methods with different names instead. Which is what you have to anyway in PHP.
Read More: Public constructors considered harmful