It is best practice not to expose the internal references of an Object (Entity). So if an Object has a field of type java.util.Date
then for example the getter for this field should return not the original date but an copy of it.
But for an java.util.Date there are two common ways to create that copy:
(Date) originalDate.clone()
new Date(originalDate.getTime())
My question is, which way is better, and why?
Because Date is nonfinal, the clone method is not guaranteed to return an object whose class is java. util. Date; it could return an instance of an untrusted subclass specifically designed for malicious mischief.
The clone() method of Date class in Java returns the duplicate of the passed Date object. This duplicate is just a shallow copy of the given Date object.
clone() when called returns a shallow copy of the object.
If it's definitely just a Date
, it won't make any difference either way.
If the actual object might be a subclass of Date
(such as java.sql.Date
) then I'd hope that clone()
would preserve the extra information (including which class it is) whereas calling the constructor wouldn't.
As an aside, if you used Joda Time you wouldn't have this problem, as there are plenty of immutable types to use. It's also a much better API :)
Read Effective Java. The preferred way to create copies is to use the copy constructor approach.
Bill Venners: In your book you recommend using a copy constructor instead of implementing Cloneable and writing clone. Could you elaborate on that?
Josh Bloch: If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. There are a few design flaws, the biggest of which is that the Cloneable interface does not have a clone method. And that means it simply doesn't work: making something Cloneable doesn't say anything about what you can do with it. Instead, it says something about what it can do internally. It says that if by calling super.clone repeatedly it ends up calling Object's clone method, this method will return a field copy of the original.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With