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 it.
But inside the same unit where this class is declared I have the choice to access the field directly or through the property.
What is the suggested best practice: direct read/write to the field or through the property that provides read and write access to it?
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:
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.
Well, this is probably a matter largely for personal taste.
Myself I would always opt for the property, even when coding internal to the class that declares the property. For example, Count rather than FCount reads better, in my view.
Another perspective would be that if you have exposed a property to the public, and it is good enough for public consumption, then it should be fine for private consumption.
Yet another take would be that if you opt to use the most publicly available interface wherever possible, then it will be more obvious when you are using something private. So, if you find that you need to write FCount because there is no Count, then you have a gentle reminder that this is a private name that you are using.
So, as I said, no definitive answer, just my own personal opinions and preferences.
If you do not use any getter and setter, it is just a matter of taste. Using the property or the field will generate the exact same code.
If you do use getter and setter, you can expicitely use the private field if you do not want to use the getter/setter code (e.g. in the constructor
).
If your getter and setter are virtual
, even if the default implementation is just an assignment, you'd have to check the SOLID principles, and ensure that you follow at least Liskov substitution and Open/Close principles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With