Posted by: lrrp | February 29, 2008

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


Responses

  1. One possible use case.

    I have a Java Calendar instance, which I get by Calendar.getInstance().
    Then I set appropriate time zone and first day of the week.
    I want to use that calendar settings in all of my classes.
    Since Calendar is mutable object, it has date/time as it’s state, I need to make sure that all classes/instances can have its own state for the calendar objects they use.
    So I created a wrapper class that holds original instance of my Calendar with all of it’s settings, and when I need instanceof Calendar I call defensive copying on my original instance.

    Just for the record…


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories