Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not an advanced topic. Moving...
 
Akshay Kiran
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic