5 Şubat 2013 Salı

some java

Defensive copies are savior

Defensive copies are the clone objects created to avoid mutation of an object. For example in below code we have defined a Student class which has a private field birth date that is initialized when the object is constructed.
public class Student {
    private Date birthDate;
     
    public Student(birthDate) {
        this.birthDate = birthDate;
    }
     
    public Date getBirthDate() {
        return this.birthDate;
    }
}
Now we may have some other code that uses the Student object.
public static void main(String []arg) {
 
    Date birthDate = new Date();
    Student student = new Student(birthDate);
 
    birthDate.setYear(2019);
     
    System.out.println(student.getBirthDate());
}
In above code we just created a Student object with some default birthdate. But then we changed the value of year of the birthdate. Thus when we print the birth date, its year was changed to 2019!
To avoid such cases, we can use Defensive copies mechanism. Change the constructor of Student class to following.
public Student(birthDate) {
    this.birthDate = new Date(birthDate);
}
This ensure we have another copy of birthdate that we use in Student class.

Hiç yorum yok:

Yorum Gönder