DEV Community

Tin Trinh
Tin Trinh

Posted on

1

Effective Java Programing Part 2 - Creating and destroying objects.

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay