This might be a very stupid question, but I have to ask it anyway. I am graduating in about a month and while studying, I have always been taught to use properties instead of public variables.
So I started wondering what the advantage was and I must say that in some cases, I have no clue at all. Of course it is handy when some other logic needs to be executed when setting properties or getting properties, but is there any advantage to using properties when you are only getting/setting 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 to programming my getter/setter like this, or could I just change the variable to public and drop the getter/setter?
If you only wrapping the access to a private variable with public getter and public setter with no further requirements to do something on setting or getting the variable you are fine using a public property.
You should think about using getters and setters if you want to inherit from your class later, and may be able to extend it in some other way, you currently don’t think about.