Question

Can anyone please tell me what is defensive copying in terms of a reference parameter to a constructor of a class in JAVA

Thanks sooooo much

Was it helpful?

Solution

Given what I can extract from the question, I guess the problem can be summarized as follows...

Let us start with this:

class NotSafeAtAll
{
    private final List<X> list;

    public NotSafeAtAll(final List<X> list)
    {
        this.list = list;
    }
}

This class has a huge problem: it copies the list reference as its member field. This means that if the caller of the constructor modifies this list, changes will be reflected in the NotSafeAtAll instance as well.

And this is where "defensive copying" comes into play. Consider:

class ALittleMoreSafe
{
    private final List<X> list;

    public ALittleMoreSafe(final List<X> list)
    {
        this.list = new ArrayList<X>(list);
    }
}

Now, the class has its own copy of the list; if the caller modifies the list it has passed as an argument to the constructor, the ALittleMoreSafe instance will not be affected.

But the story does not end here, of course. Now consider that there is a method in the latter class to return the list it has received as a parameter:

class ALittleMoreSafe
{
    private final List<X> list;

    public ALittleMoreSafe(final List<X> list)
    {
        list = new ArrayList<X>(list);
    }

    public List<X> unsafeGetList()
    {
        return list;
    }
}

You lose! Even if your constructor is safe, the fact is that you return the reference to your internal list; and the caller can modify the list via this reference.

Here again, defensive copy can save you, but there is a better solution: ensure that the list you return is immutable:

public List<X> safeGetList()
{
    return Collections.unmodifiableList(list);
}

Any attempt of the caller to modify the returned list will fail.

So, is the story over?

NO.

It can only be over if all X instances are immutable. Unfortunately, the very classical, and overused, bean pattern anything but guarantees that. But this is another story.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top