This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
If I return Collection I can return unmodifiable version from Collections class. Is there something for arrays? I know I can build another array and copy it, but maybe there is solution without performance price?
I think an unmodifiable Collection is the way to go.
But if you do end up cloning the array, then be sure that you make a "deep copy." Otherwise, the copied array will contain references to the same element objects as the original. (Yet another reason to go with the unmodifiable Collection.)
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
But if you do end up cloning the array, then be sure that you make a "deep copy."
Which would mean we're not really cloning it, right? Cloning an array returns a shallow copy.
Otherwise, the copied array will contain references to the same element objects as the original. (Yet another reason to go with the unmodifiable Collection.)
Errr... no. That is, if we're talking about an array or collection of mutable objects, then Collections.unmodifiableCollection() is just as vulnerable to abuse as a cloned array is. Try this:
Using unmodifiableList() and similar methods only protects the collection itself from modification. If the objects inside the collection are mutable, then they are not protected. If you need to make absolutely sure the data in your original collection remains unmodified, you need a deep copy. Period.
... Which would mean we're not really cloning it, right?
Yes, you're right. I was careless here -- should have said "copying" rather than "cloning."
...Collections.unmodifiableCollection() is just as vulnerable to abuse as a cloned array is...
Now, that I didn't realize. Thanks for pointing this out!
Joined: Dec 02, 2003
Safe are only unmodifiable collections of immutable objects. It seems to me that this guarding is not practical. It will steal performance and also programmer time. So it must be done for secure systems, like banking software etc mostly. The best thing I came up with - trust people who use your code Unless of course you work with very sensitive data, as mentioned before.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com