Here is a good set of guidelines for when to use properties vs methods from Bill Wagner (fixed link)
- Use a Property when all these are true:
The getters should be simple and thus unlikely to throw exceptions. Note that this implies no network (or database) access. Either might fail, and therefore would throw an exception.
- They should not have dependencies on each other. Note that this would include setting one property and having it affect another. (For example, setting the FirstName property would affect a read-only FullName property that composed the first name + last name properties implies such a dependency )
- They should be settable in any order
- The getter does not have an observable side effect Note this guideline doesn't preclude some forms of lazy evaluation in a property.
- The method must always return immediately. (Note that this precludes a property that makes a database access call, web service call, or other similar operation).
- Use a method if the member returns an array.
- Repeated calls to the getter (without intervening code) should return the same value.
Repeated calls to the setter (with the same value) should yield no difference from a single call.
The get should not return a reference to internal data structures (See item 23). A method could return a deep copy, and could avoid this issue.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…