Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Class get properties Vs. methods

When an object is required to provide some simple true/false information about itself one may use a method or a property to return a boolean value.

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.

An example of what I am talking about is:
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.

To illustrate:

A caveat I have encountered when using properties which calculate data upon access is that they may negatively affect scalability. When the class is designed, the designer may have envisioned only a few of the objects being used at a time. However, if a list of hundreds of these objects is created and then bound to a control, the get property will be called hundreds of times, calculating the return value each time. This will lead to poor response-time as the number of items increases. So if you're sure the object's property will only be used a few time in a given system operation it is ok to calculate on the fly. Otherwise it is essential to pre-populate the data, cache the data used in the calculation in a static member, or redesign/refactor the class. An elegant solution to this problem is to use the Assembler pattern in combination with DTO's, which I will discuss soon in another post.


Posted 09-27-2006 4:33 PM by Joe Niland
Filed under: ,

[Advertisement]

Comments

mgrzeg wrote re: Class get properties Vs. methods
on 09-27-2006 1:00 PM

Actually, internally properties are simply methods produced by compiler (with get_ & set_ prefixes). Technically there's no difference between methods and properties. Even if you use language, which doesn't support properties, you can acces both accessors and use them as methods.

Although they look like fields, there are many caveats while using them - they cannot be passed as method arguments by ref, can have set, get or both accessors, etc.

The method-background of properties is not so obvious and sometimes you should definitely use method instead of property. For example, for me DateTime.Now should be replaced with DateTime.getCurrent() or something, because it's calculated again and again during execution and has no field-backstore. It's value is _calculated_, so syntactically (or rather logically) method would be better.

IMO if the state of your object may be refactored to the instance boolean field, you should use it instead of property (but be careful - it's value can be changed by client. You may defend your code using property with acessors having different visibilities). If not - use instance method.

Rob Eisenberg wrote re: Class get properties Vs. methods
on 09-27-2006 1:20 PM

Good discussion here.  I'm looking forward to hearing about the Assembler pattern.  Any chance to increase my repertoir is cool.

Joe Niland wrote re: Class get properties Vs. methods
on 09-27-2006 3:31 PM

Hi, and thanks for your comments.

mgrzeg, that is a good point regarding the internal nature of properties. And it adds to the discussion because as developers we know that a property will produce the same code and same performance as the same functionality implemented in one or two separate methods. So that's one concern off the list when deciding on which to use.

I agree about DateTIme.Now, and it seems that the general consensus is that properties should not be used to expose data which is calculated on the fly; which I feel comfortable with.

These days I am moving toward having domain classes which are predominately data carriers, and BL classes which orchestrate the domain entities. Using this approach means that in general the BL objects populate the domain objects, thus keeping the internal domain class code quite simple.

Kostya wrote re: Class get properties Vs. methods
on 11-23-2007 11:27 AM
The link to the checklist is broken. Here is another one - http://dotnettipoftheday.org/tips/property_vs_method.aspx
Ben wrote re: Class get properties Vs. methods
on 03-12-2008 7:12 PM
I understand that code is more stable when variables are passed to a class via properties. However, using method parameters requires a lot less code. When do I know when to use properties and when to use a method.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)