aspose file tools*
The moose likes Beginning Java and the fly likes Use of the clone() in getters and setters for Mutable Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Use of the clone() in getters and setters for Mutable Objects" Watch "Use of the clone() in getters and setters for Mutable Objects" New topic
Author

Use of the clone() in getters and setters for Mutable Objects

Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
Hi All,
When Mutable objects such as Date objects are having getters and setters, is it a good practice to clone the objects. ex:
Instead of this;

public Date getDate() {
return dateObj;
}

have some thing like this;
public Date getDate() {
Date date = null;
if (this.date != null) {
date = (Date) this.date.clone();
}
return date;
}

Thanks & regards.


SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Not an advanced topic. Moving...


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Akshay Kiran
Ranch Hand

Joined: Aug 18, 2005
Posts: 220
I don't see any immediate advantages of the design you have used.

However, such a thing is mostly done for MUTABLE objects only, in places where you want to give out all the information about the object to the client, and yet prevent the client from making changes to the original copy.
It is a mechanism to prevent rep exposure.


"It's not enough that we do our best; sometimes we have to do<br />what's required."<br /> <br />-- Sir Winston Churchill
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Its usually done for immutable objects. I do this for all method declared on the public interface of the class. For methods that are package or more restricted scope, I do not do defensive copying.

Note: You need to do the same thing on the setter. If your really anal, you need to do this when you deserialize the class as well.
 
Consider Paul's rocket mass heater.
 
subject: Use of the clone() in getters and setters for Mutable Objects