Tuesday, September 11, 2007

Defensive Copy!

This way of programming makes sure that your code is safe 100%, even if java code is safe code
but there are still some stuff should be done by the programmer to acquire the 100% as some
clients of your class will do their best to destroy its invariants so lets move on and see how can we do this :

public class Test {
private Date start, end;
public Test(Date start,Date end){
//make check here to ensure that start is before end
this.start=start; this.end=end;}
//Getters & Setters ……}
At first you might think that this class looks good and nothing could go wrong here but re-thing again coz there is something extremely wrong could happen. Lets see how will that happen
Date start=new Date();
Date end=new Date();
Test test=new Test(start,end);
//great nothing wrong till now
End.setYear(78); //oppps
this would see the end variable inside test to 78 and this would violates the checking that we made which is to make sure that end comes after the start (for example start might be 90 and now end will be 78 and no one will complain until you invoke your business logic or you might not ever now )
So now we will re-write our class in another way(the constructor only to overcome this problem)

Public Test(Date start,Date end)
this.start=new Date(start.getTime());
this.end=new Date(end.getTime());
Now we are safe and we made something called a defensive copy in this way if the user or thread tried to change the data sent to our class nothing will happen but in the 1st case this will change the values in our class also and this would harm our code.
we are not safe 100% also coz the date is mutable object so in the getter we could do something like that
Test test=new Test(start,end);
Date date=test.getStart();
and we could change the date object
so to overcome this we could make something like the following in the getter
public Date getStart()
return starrt.clone();
so this will return a clone from the start meaning that i cant change the start and i am now safe 100%
So defensive copy is made for mutable objects which means immutable object don’t need to have defensive copy and as Date is a mutable object we need to make defensive copy for it.

No comments: