• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

encapsulation of collections

 
Tomek Ziolkowski
Greenhorn
Posts: 9
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What do you think, is it a good programming practice to do something like this:



...instead of doing this:



Dereferencing object in the first example prevents modifications of the class variable someObjects outside of the class. Are there any issues you might think of in doing something like this?

Thanks!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It really depends on the context. In some cases it's appropriate to create a new list, and in others not. And it's not really a simple "this or that" either. There are at least two other major factors to consider:

1. What does the List contain? If its elements are mutable objects, then you need to consider how deep to copy. If you just create a new List as in your example, and the List contains Dates or other Lists or any other mutable object, then, true, the caller can't modify your List, but he can modify its elements. Maybe you want that, or maybe you don't.

2. In the general case, you don't want to just expose your member variables to users of your class. Rather, you should provide methods that perform appropriate operations on your object's state. There are of course cases where it makes sense to let users see your internal data, such as that list, but you have to consider if it makes sense on a case-by-case basis, and if you can't come up with a good reason to allow it, default to not exposing it.


And welcome to the Ranch!
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's one more alternative:
Like your first example, the List cannot be modified. Unlike that example, you don't create a full copy of the entire List.

I go for this option when I want the List unmodifiable, and your second if it doesn't have to be. I hardly ever use your first option.
 
Tomek Ziolkowski
Greenhorn
Posts: 9
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys for the answers. Rob, I don't use this code technique (firs example) either , just noticed this in some places in projects I'm working on and started to think what might be a reason of doing this and any possible associated issues, as I didn't notice inside the project's code any obstacles of using the "standard" way (second example). I think it is also a matter of how different people are used to write the code etc.

...the code: seems more sensible to me in my specific case than the code in first example.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic