Consider the static factory methods over the constructors
One advantage of using factory methods over the constructors is that the factory method has a name. If the parameters that passed into the constructor is not helping to understand what object will be returned to the client code.
The factory method with a well-chosen name will help the client code easier to read.
The second advantage of using a factory method over the constructor is that it doesn't have to return a new object every time it was invoked. So this method is very helpful when we trying to create an object that will be used a lot or expensive to create. And that class will be called instance-controlled. Because the class controls the creation of its class. Those classes could be Singleton or Non-Instantiable. It allows immutable class can guarantee that no two equal instances exist. a.equal(b)
if and only if a == b
The third advantage is that it could return any subtype of its return type. This will be a good practice to return an interface as return type and has the implementation-specific class hidden.
With Java 8, the interface could have the static method. I didn't know about that or how that could help me to do anything? Why would I need a static method for an interface?
In the case of JDBC, Connection plays the part of the service interface, DriverManager.registerDriver is the provider registration API, DriverManager.getConnection is the service access API, and Driver is the service provider interface.
Top comments (0)