开发者

Is there any advantage to using properties over public variables?

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 开发者_C百科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.


Depends on the language and on if your code is used as a binary component by other code. As you say, if you need to perform some extra logic, you need getter/setters, and the need for that may arise in the future. So the question is, can you change a public variable to getter/setters if the need arises?

For example in .net, the binary signature of a property is different than the signature of a public field. So you cannot change a field to a property without recompiling the consumer code. This is not usually acceptable for a component, so you better start out with using properties. (Not sure how it works in AS.)

But if your code is not used as a component but only used as part of the same compilation unit it doesn't matter. Just keep it simple, and change the var to a property when the need arises.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜