4

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?

  • 1
    few lines after the part you refer to, book author writes: "programmer calls the freeze method on an object before using it", what is unclear to you about this? – gnat Apr 18 '18 at 11:25
  • 1
    @gnat Thanks for going through the book again. I was wondering how do we freeze an object? – Karan Khanna Apr 18 '18 at 11:51
5

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).

-1

Freezing a class would be something like:

public class Foo
{

    private int a;
    private int b;
    private boolean frozen;

    public int getA()
    {
        return this.a;
    }

    public int getB()
    {
        return this.b;
    }

    public synchronized void setA(final int a)
    {
        checkNotFrozen();
        this.a = a;
    }

    public synchronized void setB(final int b)
    {
        checkNotFrozen();
        this.b = b;
    }

    public boolean isFrozen()
    {
        return this.frozen;
    }

    public synchronized void freeze()
    {
        this.frozen = true;
    }

    private void checkNotFrozen()
    {
        if (this.frozen)
            throw new RuntimeException();
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.