views:

173

answers:

1

The Wikipedia article about encapsulation states:

"Encapsulation also protects the integrity of the component, by preventing users from setting the internal data of the component into an invalid or inconsistent state"

I started a discussion about encapsulation on a forum, in which I asked whether you should always clone objects inside setters and/or getters as to preserve the above rule of encapsulation. I figured that, if you want to make sure the objects inside a main object aren't tampered with outside the main object, you should always clone it.

One discussant argued that you should make a distinction between aggregation and composition in this matter. Basically what I think he ment is this:

  • If you want to return an object that is part of a composition (for instance, a Point of a Rectangle), clone it.
  • If you want to return an object that is part of aggregation (for instance, a User as part of a UserManager), just return it without breaking the reference.

That made sense to me too. But now I'm a bit confused. And would like to have your opinions on the matter.

Strictly speaking, does encapulation always mandate cloning?

PS.: I program in PHP, where resource management might be a little more relevant, since it's a scripted language.

A: 

No, encapsulation simply mandates the ability to control state by creating a single access point to that state.

For example if you had a field in a class that you wanted to encapsulate you could create a public method that would be the single access point for getting the value that field contains. Encapsulation is simply this process of creating a single access point around that field.

If you wish to change how that field's value is returned (cloning, etc.) you are free to do so since you know that you control the single avenue to that field.

Andrew Hare
I see what you are saying. That makes sense. Thank you.