Should you access a variable within the same class via a Property?

前端 未结 6 2019
攒了一身酷
攒了一身酷 2020-11-29 07:33

If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it.

My question is sho

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 07:59

    One of the stronger argument for accessing local (class scope) variables through properties is that you add a level of abstraction in your class. If you change any logic concerning how that field is stored then the rest of your code will be left unaffected.

    For example you might change that from a local variable to a property of a child object, to a database call, to a webservice call, to a static property on a class and so on. When making the change it gives you a single point of change, the property, and you do not have to update the rest of your class since they all use the property.

    Also using the property enables you to apply business rules on the value of the property instead of having to enforce the same rule at each location where you'd directly access the field. Again, encapsulation

    With the introduction of automatic properties there's even less reason to explicitly have a local variable, unless you need to apply business rules on the get/set

提交回复
热议问题