Is there an advantage to using properties over public variables?

This may be a very stupid question, but I still have to ask him. I finish school in about a month, and during my studies I was always taught to use properties instead of public variables.

So, I began to wonder what the advantage is, and I have to say that in some cases I don’t know at all. Of course, this is convenient when you need to perform different logic when setting properties or getting properties, but is there any advantage in using properties when you only get / set a variable? An example of what I mean is shown below (As3).

private var _myVariable:SomeClass;

public function get myVariable():SomeClass{
    return _myVariable;
}

public function set myVariable(value:SomeClass):void{
    _myVariable = value;
}

So, to repeat and clarify my question: is there any advantage in programming my getter / setter like this, or can I just change the variable to the public one and delete getter / setter?

+3
source share
2 answers

If you are only accessing a private variable using the public getter and public setter without any additional requirements to do something to set up or retrieve the variable, you can use the public property.

You should consider using getters and setters if you want to inherit your class later and maybe extend it in some other way that you don't think about right now.

+5
source

, . , , /, . : public getter/seters, ?

, .net . , . , . ( , AS.)

, , . var , .

+2

All Articles