12

Possible Duplicate:
Properties vs Methods

For many situations it is obvious whether something should be a property or a method however there are items that might be considered ambiguous.

Obvious Properties:

  • "name"
  • "length"

Obvious Methods:

  • "SendMessage"
  • "Print"

Ambiguous:

  • "Valid" / "IsValid" / "Validate"
  • "InBounds" / "IsInBounds" / "CheckBounds"
  • "AverageChildValue" / "CalcAverageChildValue"
  • "ColorSaturation" / "SetColorSaturation"

I suppose I would lean towards methods for the ambiguous, but does anyone know of a rule or convention that helps decide this? E.g. should all properties be O(1)? Should a property not be able to change other data (ColorSaturation might change R,G,B values)? Should it not be a property if there is calculation or aggregation?

Just from an academic perspective, (and not because I think it's a good idea) is there a reason not to go crazy with properties and just make everything that is an interrogation of the class without taking an argument, and everything that can be changed about the class with a single argument and cant fail, a property?

Community
  • 1
  • 1
Catskul
  • 17,916
  • 15
  • 84
  • 113
  • Community Wiki? As this seems a tad bit debatable and subjective...or re-tag this as subjective...but your question will probably end up getting closed....?! – t0mm13b Mar 12 '10 at 22:58
  • 1
    This is a duplicate question, probably several times over! Ex: http://stackoverflow.com/questions/601621/properties-vs-methods – mjv Mar 12 '10 at 23:06
  • Even something as "obvious" as "length" is not always obvious! For example, determining the length of a linked list involved traversing the entire list -- a potentially expensive operation. So you might well choose to make that a GetLength method instead, because people expect getting a property to be inexpensive. – itowlson Mar 12 '10 at 23:09
  • @mjv: I'd almost prefer to close after seeing the that there are duplicates, but after looking I noticed that the duplicates questions answers are both weak. I think the question and answers here are more in-depth, and therefore worth keeping open. – Catskul Mar 12 '10 at 23:20
  • There are no fewer than 12 duplicates or near duplicates in the top 100 hits when searching SO for "property method". I found some very good and relevant answers there. In fairness had this question, here, not been closed, you may have gotten better answers yet (but then again, statistics are not good). Also, your question was in several ways better than several of the duplicates. Please, try and remember to first search SO, if only briefly, before posting questions; this will either provide a direct answer, or allow you to better frame your own question. – mjv Mar 13 '10 at 01:44

6 Answers6

10

I typically convert a property to a function if it has one of the following behaviors

  • Causes a side effect (other than setting the backing field)
  • Implementation is expensive when compared to say a field access
  • Implementation has higher complexity than Log(N)
  • Can throw an exception
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • @JaredPar: See http://stackoverflow.com/questions/448575/method-or-property-in-c/448599#448599 I know you answer a lot of Qs on SO, but when this kind of perennials show up, it would be nice to limit such noise. I doubt you're in for the reps, so why not help keep SO tidy. Thanks. – mjv Mar 12 '10 at 23:16
  • @mjv, already past rep cap for the day so not in it for the rep :). Interesting to know I've answered this question before. But then again I've given 3000+ answers in the last ~15 months and it's hard to keep them all in your head. That particular answer was given over 1 year ago. – JaredPar Mar 12 '10 at 23:33
  • 3
    @mjv (cont) In general though I don't spend a whole lot of time searching out duplicates. If I look at a question and know for sure or extremely likely is a dupe, I'll bother to search it out. Otherwise I don't because I'd rather spend time helping people than giving them the equivalent of a virtual smack for asking a question. Also in this case while that question is likely a dupe of this one, the one it's duped against is not. Read the original one closely and it's asking when should a field not be exposed as a property. – JaredPar Mar 12 '10 at 23:34
  • @JaredPar: Apologies for apparently singling you out on this; all major (and not so major as myself) contributors are probably "guilty" of duplicate answers at various points in time. incidentally I failed to notice the "2009" in the referenced answer of yours and thought it was only a few weeks ago. I did contact you because I've come to respect you, for all your precise and well informed answers, and also for my guessing, correctly, that reps were not what kept you going ;-) I therefore wanted to know why you didn't pay so much attention to duplication. With regards to the question... – mjv Mar 13 '10 at 00:16
  • (cont) of `property vs. method`, it truly is a perennial question: you'll find no fewer than 12 duplicates or near duplicates in the the top 100 questions found with a "property method" search. Even allowing for a few cases where the Q may effectively be a false positive, and possibly allowing for a few "near duplicates", with ever subtler semantic twists, there's ample evidence that any thoughtful questioneer could find a [typically] better answer by taking a few mintutes to research it on his/her own. A kind "See this link" in the comment section is therefore no so much a virtual smack ... – mjv Mar 13 '10 at 00:18
  • (cont) ... than a kind nudge toward a better SO repository and community. Sorry for so much verbosity and "meta" type discussion. I guess I care about all this ;-) – mjv Mar 13 '10 at 00:18
  • @mjv, no worries on singling me out. I don't mind at all, I actually got a bit of amusement at reading my old answer. But yes in retrospect this is a fairly common question and if I hadn't been in so much of an answer mode I likely would have searched for a dupe. – JaredPar Mar 13 '10 at 02:13
5

I´ve found some interesting text about this

MSDN | Properties vs Methods

EDIT

It says things like:

Use a property when

  • The member is a logical data member

Use a method 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.
Javier
  • 4,051
  • 2
  • 22
  • 20
4

Another consideration is bindability. Most frameworks can bind only to properties. For example, if you want IsValid to be usable in binding (say, as a binding sourcee for the OK button's IsEnabled property), then it has to be a property rather than a method.

itowlson
  • 73,686
  • 17
  • 161
  • 157
1

In deciding whether to use a property or a method you should also consider the ammount of work the method involves. I.e. if it is relatively cheap to retrieve the value make it a property, if it costly make it a method.

AxelEckenberger
  • 16,628
  • 3
  • 48
  • 70
0

If you can calculate something from what you already have, use methods, if your value has to be a basis for operating with or calculating something else it should be property.

For example, if you want to check whether certain user input is up to date and you can do it with your unique patented algorithm, use method Validate(). If user just sends you a form submitting nis current address is valid, use property valid. But it is just a common approach that may vary depending on what you actually want.

Zmicier Zaleznicenka
  • 1,894
  • 1
  • 19
  • 22
  • Methods and properties have no difference in memory usage or execution speed. A property is just syntactic sugar for a pair of methods (or even just a single method for read-only or write-only properties). You may be thinking of fields rather than properties. – itowlson Mar 12 '10 at 23:11
  • You're right, my mistake. Removed. – Zmicier Zaleznicenka Mar 12 '10 at 23:31
0

I personally make the choice on complexity and what the method/property is going to do. If I'm all doing is setting a value, ie _name = something;, then I go with a property. Even if I'm going to do some very basic calculations or conditional statements I will stick with a property. But if something is going to need some serious work or even moderate work I would use a method. Nothing aggrevates me more then setting a property and suddenly a whole bunch more code than I expected gets executed.

Justin
  • 4,002
  • 2
  • 19
  • 21