Wednesday, July 19, 2006

What is Defensive Copying

I was wondering what to blog about and then I saw the term defensive copying. I have heard this term mentioned a few times but wasn't sure quite what it was. So I thought it was time for a bit of investigation.

So what is defensive copying, also sometime known as object copy.

Defensive copying is concerned with protecting mutable objects e.g. objects who's state can be modified by the user. If you were pass back the reference of an object any changes a user made to that copy of the object would effect your object because you are only passes a reference to the object and not the actual object itself. This is known as a shallow copy.

To avoid users being able to change the values of your object you can pass back a defensive copy. This means that instead of passing back a reference to your object it passes back a new object but with the same values. This means that any changes the user makes to that copy of the object doesn't change the value/state of your object.

It's an interesting idea but I can't think of a use for this at the moment but I'm sure one day this will come in useful.

Here are a couple of links to some probably better explanations with an example

http://www.javapractices.com/Topic15.cjp


http://en.wikipedia.org/wiki/Defensive_copy

The first site Java practices has lots of useful articles and well worth checking out

(http://hoskinator.blogspot.com/2006/07/what-is-defensive-copying.html)

No comments: