Best Practice on local use of Private Field x Property

后端 未结 9 1613
萌比男神i
萌比男神i 2021-01-22 02:09

When inside a class you have a private fiels and expose that field on a public property, which one should I use from inside the class?

Below you is an example on what I

相关标签:
9条回答
  • 2021-01-22 02:55

    I always use the property accessors, because the I am safe in case I add logic in the getter or setter in the future, knowing for sure that no code bypasses it.

    0 讨论(0)
  • 2021-01-22 02:56

    Thank you all for the answers and suggestions.

    After considering all the suggestions here plus other researches it is my impression that for this situation on Private Field versus Assessor it is more of a personal choice. So basically the most important is that no matter what you choose be consistent.

    That said; my personal rule is leaning towards this:

    1. Access your private fields directly.

    2. If accessing accessors use the keyword ME. to improve readability

    3. Use the accessor only if it implements vital logic logic that also applies to private access. This way you know that if you are using the accessor it is because there is "something else to it"

    4. Avoid using Protected Fields. Derived classes should always use the accessor, never direct access to the field.

    Let me know what you think.

    SideNote:

    After this I think we are missing a new scope for the class level fields. A keyword like “Restricted” where this field could only be accessed from its getter/setter. This way you always access directly the private fields, but if you need to make sure certain field can only be accessed by its accessor that you change the Private to Restricted. (how about "Restricted , RestrictedRead and RestrictedWrite"?)

    0 讨论(0)
  • 2021-01-22 02:56

    I prefer to use the property whenever possible. This gives you the flexibility in the future to modify what the property returns/sets without having to go through and find all the locations that were using the private variable.

    0 讨论(0)
提交回复
热议问题