Friday, October 18, 2013

Properties, Functions, and Variables

Many people get confused when to use a function, a property, or a variable.  Many variables are simple properties while many properties are simple functions.  So how do you know when to use what?

Variables and properties can act identical to us developers.  There are two main reasons why you may want to use a property instead of a variable.  The most notable is that you can data bind properties.  You cannot do that with variables.  The other reason are with libraries.  If you were to add logic that would change the type from a variable to a property then you may have just broken all of the client code.  They are fundamentally different in the underlying system.  With that said, there is no real good reason to just use a variable.

Properties and functions are slightly different in a few ways.  Microsoft says that we should use methods when: (, 2013)
  • 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. 
There is one thing that is missing from this list, but is considered a best practice more than a rule.  Exceptions should never be thrown when reading from a property.  Trying to avoid exceptions in properties would be even better, but isn't always feasible.

Bibliography: 2013. Property Usage Guidelines. [online] Available at: [Accessed: 18 Oct 2013].

1 comment: