Using properties instead of fields in class methods of the same unit is a bad practice?

前端 未结 3 1866
太阳男子
太阳男子 2020-12-20 20:36

I have declared a private field and a public property for a given class.

From other units I can access the field through the public property that provides access to

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 21:07

    Contrary to David's taste, I always use the private/protected field, but only within the same class (when private) or within a derivative (when protected). Strangly enough, the reason is readability for me too:

    • By now, FCount reads as Count,
    • Using the private field makes it clear I am working on internals,
    • And in the sporadic situation where I use the property, then it is obvious that I need to trigger the setter or getter behind it.

    The key point here is being consistent. Choose one, and stick to it. There is no right nor wrong.

    Update due to Jerry's comment:

    My point about being consistent is a general advise for everyone's own benefit. Accustom yourself with one default syntax, and your code will be crystal clear (to you I mean) for the rest of your life.

    Of course, when you choose using private fields, there will be incidental situations you must use the property instead. But this applies vice versa: if you choose to use the property, then there will be situations you have to use the private field. I am only saying that when you stick to a system, the exceptions will more clearly look like exceptions.

提交回复
热议问题