If the variable is private , I often do not create a property for it. If it is in any way exposed to an external type, I always expose it through the property for various reasons:
- It may not be necessary today, but if it is needed later, it will be a breaking change
- Working with data only works on properties, not on fields (I think not a big user of data binding).
- It allows you to insert validations, logging, breakpoints when accessing a value
In addition, if a field is opened through a property, I always get it through a property, even inside a class.
Update
In response to your updated code samples: here are a few things you can consider around code design.
- Readability versus Speed
- atomicity
- Other side effects
One typical tip (which I find very good) is to "write for clarity, a performance test." This means that when you write your code, your first problem is whether it is clear what the code does when viewing it. This is often (but not always) more important than raw code speed. Optimize recording speed when you set where you get it. Access to the property will be slightly slower than reading the field directly, but in most cases the difference will be insignificant (if at all measurable).
Atomicity can be a problem. Given your sample code, we have a speed field that is open through the speed property. If the MultiplySpeed method needs to perform several updates for a value, these intermediate values will be available through the speed property at different times while the calculation continues. This is true whether you are updating the field directly or through a property. In such cases, it might be better to first put the value in a local variable, use it for calculations, and assign the value to this variable when it is done.
Finally, other side effects. Perhaps a change in speed should result in an event (e.g. SpeedChanged ). In such cases, it is also probably a good idea not to update until the calculation is complete.
I like to think of property as a contract, and the field as implementation. Anyone (with the exception of a kernel of my type) that needs cost should use a contract. Based on the implementation should be done only if there are sufficient grounds for circumventing the contract.
And yes, if you encapsulate access to a field in a property, naturally changing the field name will require fewer updates (and perhaps also the field name becomes less important).
I hope this makes sense, and not too much from the topic;)
Fredrik Mörk Feb 17 '10 at 17:45 2010-02-17 17:45
source share