I’ve often seen the following described as the “correct” way of implementing get/set methods:
public class Foo {
private var _someVar:SomeClass;
public function get someVar():SomeClass {
return _someVar;
}
public function set someVar(newValue:SomeClass):void {
_someVar = newValue;
}
}
Now, because AS3 is returning always references to Object classes, when we use the “get” method we obtain a reference to our private var => encapsulation is broken.
Even if we don’t have a set method we can modify the privar var !
What is the purpose of setting it as private then?
The only solution that I found to this is to return a clone of “_someVar” in our get method, but I’ve never seen this in any example.
So I think I’m losing something here.
Are you returning a clone object from your getters or you just accepting the break in encapsulation?
EDIT
I understand how set and get methods works, and I understand the benefits of them.
I’m asking for the break of “private” access in our private var when we return it with a getter by reference (if our var is of type Number, String, int, etc AS3 is returning always by value, not reference, so we don’t have problem here).
Maybe is not the encapsulation which is broken, because we can’t set the property without a setter method. But we can modify it !
See this example:
public class Foo {
private var _someVar:Array; // note that this is a Object (not Number, String, etc)
public function Foo(){
_someVar = ['don't touch this!'];
}
public function get someVar():SomeClass {
return _someVar;
}
// note that we don't have a setter
}
var f:Foo = new Foo();
var a:Array = f.someVar;
trace(a[0]); // 'don't touch this!'
a[0] = 'why not?';
trace(f.someVar[0]); // 'why not'
So, we are changing our private var from outside, and without control, even when we don’t have a setter method.
You are controlling access to the member variable when you use get/set functions. For example, if you want the variable to be “read-only” from the outside, but editable from within the class instance you make a get function so that it can be read from outside but do NOT create a set function. This is different from using a private const, because that must be declared immediately and can never be changed from anywhere.
Similarly, using these functions can allow you to create side-effects for setting the property. For instance:
EDIT : Because you’ve updated the question to be more specific, here’s an update of my own.
You normally would NOT do that. If you’re trying to protect the variable itself, then you won’t offer access to it directly. Doing that breaks “the law of Demeter”. For your specific example with the array, you might do something like this:
As a different example, using a theoretical complex object…
That last one is interesting because you don’t need to expose to the world that you’re using SomeObject to do the work… you’re just advertising that you yourself can do it.