The question is which is preferable to use? Or does it even matter. I'm sure there are solid design reasons for going either way.
e.g. bool-returning method - IsBlah() - Vs a [possibly readonly] property - IsBlah.
Each will provide its return value depending on the internal state of the object. The syntax will differ, as well as the accessibility (properties can have mutators). What else is different?
One major difference is that in C# a property with both get and set accessors can be inadvertently assigned to via a small typo:
if (obj.State = serverState)...
when you mean,
if (obj.State == serverState)
Obviously this can be avoided by only providing a get accessor, however this can't always be done because some properties need mutators too. Another fix would be to enforce a coding style where the comparison value always appears on the LHS of the comparison - not stable though, as it depends on the developer.
Bill Wagner at SRT Solutions suggests that there are no hard-and-fast rules, but that some simple guidelines may be followed in order to make the decision. This checklist can be found here. Some good points he makes in favour of properties is that they can be serialised, which is definitely becoming more and more important as web services gain popularity. In the context of .NET this also affects objects sent over a Remoting boundary.
Personaly, I prefer to use properties whenever possible as they fit well with the concept that they are exposing an attribute of the object. I definitely agree with Bill in that they should be simple, settable in any order, and should not call outside the object to determine their value. I think it is wise to use private methods to calculate properties based on external data, and then cache that result for when it is required via the property. This can be done when the object is created.
As always, it depends on the particular requirements for the object. If the attribute in question can be safely calculated from internal state at any time in the object's lifetime, then a property is the way to go. If the attribute can only be calculated after the constructor has finished, or if the attribute depends on external data, a calculation method and caching solution, or a re-design/refactoring would be preferable.
1 comment:
The link to the checklist is broken. Here is another one - How to determine whether a property or a method is more appropriate for your needs
Post a Comment