Defensive coping

Defensive copying is used for protecting the field of an object from being changed by all non native class. Sometimes if we do not use defensive copying our object may hold incorrect data. For eg:

import java.util.*;
 
public class Test {
	private Date today;
 
	public void setToday(Date dt) {
		this.today = dt;
	}
 
	public Date getToday() {
		return today;
	}
 
	public static void main(String args[]) {
		Test t = new Test();
		Date dt = new Date();
 
		t.setToday(dt);
 
		System.out.println("Actual :: " + t.getToday());
 
		dt.setYear(2000);
 
		System.out.println("Current :: " + t.getToday());
	}
}

The output of the above program will be.

Actual :: Mon Jan 07 12:29:43 IST 2008
Current :: Sun Jan 07 12:29:43 IST 3900

In the above program changing the dt object changes t object data also. To prevent this we use defensive copying. The fix for this will be to create a defensive copy of the object in the setter. For eg:

public void setToday(Date dt) {
	this.today = new Date(dt.getDate());
}

Now if we run the program the output will be

Actual :: Mon Jan 07 12:29:43 IST 2008
Current :: Mon Jan 07 12:29:43 IST 2008

Did you like this? If so, please
tell a friend
about it, and subscribe to the blog RSS feed.

Share/Save/Bookmark

If you enjoyed this post, make sure you subscribe to my RSS feed!



Related Posts:
  • Recursively delete a directory
  • Sending an e-mail using WebSphere Mail session settings.
  • Sorting an ArrayList of objects.
  • LIKE clause with PreparedStatement
  • Exception stackTrace to a String Variable


  • No Responses to “Defensive coping”  

    1. No Comments

    Leave a Reply