Object-oriented – Using static to create an immutable object

immutabilityobject-orientedstatic methods

I was reading on this software engineering page about the use of static methods. However, I'm confused, and maybe it's about the context in which it talks about static. The idea is, that static is really bad for testing and shouldn't be used.

When creating immutable class, sometimes the constructor is private and a static factory is used to create the object. Even Java's own documentation supports the use of a factory when creating immutable objects.

A more sophisticated approach is to make the constructor private and
construct instances in factory methods

Best Answer

If you are making an immutable DTO, where you simply bundle up a bunch of properties and that's it, such as your example, then just use a public constructor.

Factories are for situations where object construction is complicated, expensive, where you return different types based on the input values, or other "logic intensive" situations. Simply storing a handful of values is not one of those situations.

Related Topic