What are the benefits of using properties internally?

后端 未结 5 714
猫巷女王i
猫巷女王i 2020-12-10 19:19

Encapsulation is obviously helpful and essential when accessing members from outside the class, but when referring to class variables internally, is it better to call their

5条回答
  •  -上瘾入骨i
    2020-12-10 19:49

    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.

提交回复
热议问题