• Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing Objects as Defensive Copies  RSS feed

 
RaviNada Kiran
Ranch Hand
Posts: 528
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any performance or security thing if we pass objects in this way ??



//Rather than directly passing al ??

[Nitesh: Use code tags.]
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37181
515
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ravi,
The performance isn't likely anything to worry about. It's more important to have working code than hope the caller doesn't modify the original list.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[teachy mode]
You don't pass objects, you pass references to objects. Using the wrong words leads to wrong concepts leads to bugs.
[/teachy mode]

Bill
 
RaviNada Kiran
Ranch Hand
Posts: 528
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jaenne .
 
Rob Spoor
Sheriff
Posts: 21048
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you only care about calling code not modifying your original list, you could also look at Collections.unmodifiableList (and its siblings for other collection types). That's a little more efficient - it does create a new object, but the internal structure is not copied. It is merely a wrapper that does not allow for any changes to the list.

If there is no such wrapper (e.g. for java.util.Date), copying is the safest way to go, as Jeanne said.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!