Java – How do we freeze an object while constructing an object using JavaBeans pattern

constructorsdesignjava

Going through Effective Java, Joshua Bloch states that the drawback of using JavaBeans pattern is that an object may be in an inconsistent state partway through the construction and with JavaBeans pattern, we cannot make our class immutable. I have understood this much.

He also says that we can reduce these drawbacks by "freezing" the object when its construction is complete and not allowing it to be used until frozen.

Can someone help me understand what does "freezing" the object means?

Best Answer

Effectively, "freezing" just means throwing lots of exceptions:

  1. Whilst the object is being constructed, any attempt to read from it (via getters or methods), results in some sort of "still being constructed" exception being thrown.
  2. When constructed and "frozen", any calls to setters or methods that could change state then result in "we are now frozen" exceptions.

This is a messy pattern and I do not believe it widely used. A far neater pattern is the builder pattern. The idea there is that you have one object (the builder) that is mutable and can be constructed in stages. Once complete, it then emits an immutable object that is then used in subsequent operations.

If the pattern sounds familiar, it because this is exactly how the StringBuilder class works (thus the name).

Related Topic