• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 10336
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not an advanced topic. Moving...
 
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic