Sunday, February 26, 2012

When to use Properties vs. Methods

From “Design Guidelines for Class Library Developers” comes the guidelines on how to chose whether you should use a property or a method: http://msdn.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx#cpconpropertyusageguidelinesanchor1

Here is the info (copied from the MSDN page):

  • Use a property when the member is a logical data member. In the following member declarations, Name is a property because it is a logical member of the class.
  • Use methods when:
    • The operation is a conversion, such as Object.ToString.
    • The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
    • Obtaining a property value using the get accessor would have an observable side effect.
    • Calling the member twice in succession produces different results.
    • The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
    • The member is static but returns a value that can be changed.
    • The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code.

Other guidelines:

Do not use write-only properties.

The following rules outline guidelines for using indexed properties:

  • Use an indexed property when the property's logical data member is an array.
  • Consider using only integral values or strings for an indexed property. If the design requires other types for the indexed property, reconsider whether it represents a logical data member. If not, use a method.
  • Consider using only one index. If the design requires multiple indexes, reconsider whether it represents a logical data member. If not, use a method.
  • Use only one indexed property per class, and make it the default indexed property for that class. This rule is enforced by indexer support in the C# programming language.
  • Do not use nondefault indexed properties. C# does not allow this.
  • Name an indexed property Item. For example, see the DataGrid.Item Property. Follow this rule, unless there is a name that is more obvious to users, such as the Chars property on the String class. In C#, indexers are always named Item.
  • Do not provide an indexed property and a method that are semantically equivalent to two or more overloaded methods.

And don’t forget the property naming guidelines: http://msdn.microsoft.com/en-us/library/fzcth91k(v=vs.71).aspx

  • Use a noun or noun phrase to name properties.
  • Use Pascal case.

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.