If the variable is private
, I will often not create a property for it. If it is, in any way, exposed outside the type, I always expose it through a property for different reasons:
- It may not be necessary today, but if it becomes necessary later it's a breaking change
- Databinding works only on properties, not on fields (I think, not a big databinding user)
- It allows to insert validations, logging, breakpoints when accessing the value
Also, if the field is exposed through a property, I always access it through the property, even within the class.
Update
In response to your updated code samples: there are a number of things to consider around the code design here.
- Readability vs. Speed
- "Atomicity"
- Other side effects
One typical piece of advice (that I find very good) is "write for clarity, test for performance". That means that when you write your code, your first concern should be whether it is clear what the code does when looking at it. This is often (but not always) more important than the raw speed of the code. Write speed optimizations when you have established where you gain it. Accessing a property will be a tad slower than reading the field directly, but in most cases, the difference will be negligible (if at all measurable).
Atomicity may be an issue. Given your code sample, we have the field speed
, that is publicly exposed through the property Speed
. If the method MultiplySpeed
needs to perform several updates to the value, those intermediate values will be available through the Speed
property at different times while the calculation is ongoing. This is true regardless of whether you update the field directly or through the property. In cases like this it is perhaps better to first put the value into a local variable, use that for the calculations and assign the value of that variable back to the property when done.
Lastly, other side effects. It could be that changing the value of Speed
should raise an event (such as SpeedChanged
). In cases like that, it is also probably a good idea not to make the update until the calculation is done.
I like to think about the property as a contract and the field as implementation. Anybody (except for the core of my type) that needs the value should use the contract. Relying on the implementation should be done only if there are good reasons to bypass the contract.
And yes, if you encapsulate the access to the field in the property, naturally changing the name of the field will require less updates (and perhaps also the name of the field becomes less important).
I hope that makes sense, and is not too much off topic ;)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…