Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use GetXXX() method and when a Getter property

There are some .NET libraries which use methods for accessing object data instead of getters i.e HttpWebResponse.GetResponseStream().

Also there are examples of accessing an stream by a property i.e HttpResponse.OutputStream.

My question is when to use which form of access and why ?

like image 445
Xaqron Avatar asked Jan 12 '11 16:01

Xaqron


4 Answers

See the FxCop rule: CA1024: Use properties where appropriate.

like image 67
TrueWill Avatar answered Oct 20 '22 06:10

TrueWill


Good question. Although a property is little more than syntax sugar for a pair of get/set methods, there two should be used in different times.

Generally, you should use a property-style getter when:

  • The value to be returned represents field-like data (generally primitives/value types, but a reference to another domain object is also fine)
  • The calculation, if any, to produce that value is relatively cheap/side-effect free
  • Getting the same value twice will produce the same value given the same inputs

Generally, you should use a getter method when:

  • The returned object is created for the purpose (e.g. factory methods)
  • Evaluating the returned value requires side effects (e.g. touching a file system, database, or changing other values)
  • Getting the return type twice will produce two distinct results (i.e. two Streams, db connections, etc).

In a sentence, if conceptually speaking the value needed is something the object HAS, use a property. If the value needed is the result of something the object DOES, use a method.

like image 36
KeithS Avatar answered Oct 20 '22 05:10

KeithS


Good question. This article brings up a few good points. In general, I use methods when the computation is expensive and properties when computation is not expensive (i.e. a stored value is returned).

like image 40
Bernard Avatar answered Oct 20 '22 06:10

Bernard


My opinion which, I'm sure, will get to -10 real fast, is that you should only use properties for serialization. In all other cases explicit method call is preferable because when you look at it, you know that a method with possible side effects is being invoked.

I guess the "correct" (tm) answer is that when all your method would do is return the value, it is ok to use getter/setter, but if there is any work to do, use a method.

like image 31
MK. Avatar answered Oct 20 '22 05:10

MK.