开发者

What are the benefits of using properties internally?

Encapsulation is obviously helpful and essential when accessing members from outside the class, but when referring to class varia开发者_如何转开发bles internally, is it better to call their private members, or use their getters? If your getter simply returns the variable, is there any performance difference?


There shouldn't be a significant performance difference, and the reason you stick to using the properties is because that's the whole point of encapsulation. It keeps all accesses of those private members consistent and controlled. So if you want to change the property getter/setter you don't have to think "do I need to duplicate the same functionality elsewhere in the places where I decided to access the private member directly?"


Accessing the field directly or using the getter usually doesn't make a big difference, unless your getter performs some lazy initialization or other processing. So it depends on what the getter does, but my rule of thumb is to always use the getter except in specific cases.

To assign a value to the field, don't forget that setters often include validation code or raise an event. In that case you should always use the setter.


The benefit would be in the cases where there was validation to be done on the Get or Set. This would be in one place and always called.

As far as I know (from other questions asked on Stack Overflow) when the Getter simply returns the value the code generated is the same as for accessing the variable directly.


The performance difference is neglectable, in about 98% of the time.

You should always use properties even though your getter or setter just get or set your private member. This will allow you to bring changes as your application evolves. Doing so, you'll be able to bring some restrictions or some other encapsulation within your properties without breaking your code. Otherwise, once you decide to write properties because of a reason X, you'll find yourself obliged to refactor all of your code to get or set the property instead of your private member.


I like to use internal properties for lazy initialization, where in the property you make sure the object is initialized. This ensures I am not using class level variables that have not yet been initialized.

TestClass1 _class1
internal TestClass1
{

get
{

    if (_class == null)
     _class = new TestClass1()

    return _class1

}

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜