Derik Whittaker

Syndication

News


Is that a Property or a Method?

This is just a quick little rant on my part.  In my opinion a property should be used for simply getting/setting of a value.  You should NOT have any logic inside your getter/setter (ok, I will add a 'caviot' to this rule and say that I am ok with doing string formatting on the getter).  If you need to have logic in either your setting or your getter I think it is about time to use a method, not a propery. 

WHY?
Because, once you start adding behavior to the property you are masking this behavior and a method will better convey your intent.

Again, this is just my thoughts/opinion, but I like to convey intent of methods/logic and wrapping logic inside a property does not convey intent.

Till next time,


Posted 07-09-2009 9:28 AM by Derik Whittaker
Filed under: ,

[Advertisement]

Comments

josh wrote re: Is that a Property or a Method?
on 07-09-2009 11:17 AM

If you do this, why even have a property in the first place? ie. see the two code samples below - they are logically and functionally the same and one is 11 lines less:

private int _variable;

public int Variable

{

  get

  {

     return _variable;

   }

  set

  {

      _variable = value;

  }

}

versus

public int Variable;

In terms of code reability and understandability, I would go with the one liner - simple, direct, and 11 lines less to write.

-j

Simone wrote re: Is that a Property or a Method?
on 07-09-2009 11:53 AM

What about some kind of caching? or handmade lazy loading? Will that be considered "logic" or is it good to put into the getter?

Stephen wrote re: Is that a Property or a Method?
on 07-09-2009 11:54 AM

I disagree with you on this one josh, access to your public fiield "Variable" cannot be restricted. with setters and getters, you can implimente a much more robost business implimentation by restricting the setter to maybe internal or private. this is especially true if you want to set the value of "Variable" after the class has been instantiated. You can also have a property on the same line

public int SalesCount { get;  private set; }    :P

KG2V wrote re: Is that a Property or a Method?
on 07-09-2009 1:28 PM

Another one - I often use the setter to set a "dirty" flag for the instance - that way I can check to see if any data changed

Harry M wrote re: Is that a Property or a Method?
on 07-09-2009 3:03 PM

There are LOTS of reasons you might want to do something inside a getter or setter. Pretending to yourself that objects dont do things in there, and getting annoyed when they do is going to end up causing a lot of wasted time.

Derik Whittaker wrote re: Is that a Property or a Method?
on 07-09-2009 3:07 PM

@Harry,

If you want to perform 'real' actions in your getters/setters i would suggest that having a GetFoo() method or SetF00() method would be a better way to convey intent.

Curtis Allen Gibeaut Jr. wrote re: Is that a Property or a Method?
on 07-09-2009 4:17 PM

Property Setters get functional code in them when you are doing MVVM with WPF.  There are a few reasons you may need to.  Especially when you start dealing with DependencyProperties.

Victor Kornov wrote re: Is that a Property or a Method?
on 07-09-2009 4:22 PM

Properties are and have always been just a little better syntactic alternative to methods, even if not in every situation. Why better? You get by w/out () which reads better. Plus all the little things like obj.Prop; won't compile, which is often a desirable effect when building FI. Overall, I think design of Properties\Methods have been overlooked by MS. While Properties have their place they require judicious use to avoid 'obscure' programming mistakes and logic 'hiding'. That comes as a surprise when you think how Properties are being told to be a good thing for encapsulation... which they often help to break, not maintain.

Michael Meadows wrote re: Is that a Property or a Method?
on 07-09-2009 4:40 PM

What about raising a changed event when a setter is called (if the value is different)?

What about capturing the original value when a setter is called?

What about lazy loading a value when a getter is called?

Harry M wrote re: Is that a Property or a Method?
on 07-09-2009 5:05 PM

@Derek Its too late for that. The properties doing stuff cat is out of the bag and if you're working with c# then  y.Foo ==y.get_Foo()

class FooBar{

int Foo {get;set;}

int get_Foo(){return 1;}

}

won't even compile. If you are worrying about properties hiding away business logic you are thinking properties are something they are not.

Derik Whittaker wrote re: Is that a Property or a Method?
on 07-09-2009 5:07 PM

@Harry,

I do not agree.

Foo {get;set;} should mean pull simple data back, with little to NO logic behind it

GetF00() can mean hitting db, hitting other resources ect

The diff is huge

theparticleman wrote re: Is that a Property or a Method?
on 07-09-2009 5:49 PM

I think this is a troll-y post (if such a term exists).  As such I wouldn't respond to it, but I usually enjoy Derik's posts.  

I agree that people shouldn't abuse their ability to put logic in properties.  But saying that you should "not have any logic inside your getter/setter" ever, ever, in a million, bazillion years seems very naive.  As others have pointed out, isn't that the point of a property?  (Adding the ability to set different access modifiers on the getter vs. the setter introduced another reason to have properties, but .NET 1.0 did not have that feature.)  I agree that you probably shouldn't be hitting a database or some other significant operation in a property.  But saying people shouldn't ever do anything in a property other than string formatting just seems like an attention getting argument.  Here's another: I know!  Let's all switch back to Java and abandon C#!  Then all of our getters and setters will be methods and we can do whatever we want in them, because Derik said it's okay to do whatever you want in a method!

So congratulations, you got me to respond, which is what you were after in the first place.  But if you keep posting stuff like this I'm unsubscribing from your RSS feed.

Ian Nelson wrote re: Is that a Property or a Method?
on 07-10-2009 6:12 AM

@KG2V - dirty flags on an object? Why does your object need to know if it has been changed? Leave such concerns to the persistence layer.

KG2V wrote re: Is that a Property or a Method?
on 07-10-2009 6:49 AM

Ah, Objects IN the persistance layer?  I'd say 50% or so of the code I write is in our persistance layer - I write only a trivial amount of UI

Ian Nelson wrote re: Is that a Property or a Method?
on 07-10-2009 8:15 AM

@KGV2. I think we must be talking at cross purposes here. I'd contend that your object model should not need to know how (if at all) it is persisted, and therefore should not require dirty flags.

Tuna Toksoz wrote re: Is that a Property or a Method?
on 07-10-2009 8:37 AM

@KGV2

You can achieve dirty check with proxies, either compile time or runtime. This is more like a field where AOP comes in handy.

JH wrote re: Is that a Property or a Method?
on 07-10-2009 10:10 AM

I agree that get/set is likely not always the most clear way to express intent.

e.g.

string Address { get; set; } vs. Address Address { get; set; }

class Address {

   public string ToString() {

    .... formatting

   }

}

but, with that, there are definitely exceptions to the rule.

Hudson Akridge wrote re: Is that a Property or a Method?
on 07-10-2009 10:48 AM

Michael Meadows pretty much hit on what we have for logic in many of our setters/getters.

Lazy initialization and before/after changed events (very important for our custom business formula system).

Michael Meadows wrote re: Is that a Property or a Method?
on 07-10-2009 11:22 AM

I think the problem is that there needs to be a distinction made between "business logic" and "meta behavior." I definitely agree that business logic does not belong in properties.  It can be argued that meta behavior could be solved with AOP, but in actuality, the weaving is just wrapping the meta behavior around the property call, so it can be argued that in the aggregate, the executed code is exactly the same if it's done by AOP or just hard coded in to the property (although AOP is arguably easier to maintain).

Nicholas Piasecki wrote re: Is that a Property or a Method?
on 07-11-2009 10:31 AM

My internal rule is that I can do whatever processing I want in properties, but if I want to convey that a get operation will either take a long time, should be cached, calls across a network boundary, or may otherwise fail spectacularly, then I'll create a GetFoo() method. It really does say that "hey, this is really churning away at something here, copy it into a temp variable instead of accessing it 20 times in a loop." But I find that it's pretty rare that I have to do such a thing.

I think saying that properties should just be simple getters and setters is a bit extreme--at that point, it really is not much better than a public member. I know Microsoft officially recommends that properties should be able to be set in any order, but in a domain model, I don't buy it--your persistence mechanism should be able to hydrate objects intelligently, letting you use properties for what they were intended for.

Andrew wrote re: Is that a Property or a Method?
on 07-13-2009 3:11 PM

Nice ridiculous overreaction there Particle Man, well done.

Putting logic code in Properties ranks up there with just blindly eating exceptions.  Yes, you can do it, but you better have a damned good reason why.  The reality is in 99% of the either case the person writing the code doesn't really know what they are doing and there is likely a much better solution to the problem.  

Dave Schinkel wrote re: Is that a Property or a Method?
on 07-23-2009 10:50 AM

Ok, but you didn't really state what you mean by "logic".  So lets continue this conversation.

What about something like this:

           public List<LandingPageLink> LandingPageLinks

           {

               get { return Catalog.Default.GetLandingPageLinks(this.id); }

           }

my property calls a Business Layer method to go grab a list of LandingPageLinks.

So it's calling a method which is pretty common and I'm only specifying one line in my property.

Dave Schinkel wrote re: Is that a Property or a Method?
on 07-23-2009 11:03 AM

@josh

because global variables are BAD (even to the point of being so careless, you could jepardize the entire application).  They completely go against the concept and reason we have OOP and the entire purpose of encapsulation using private fields and properties to publically expose values outside your class to the consumer.

It's a sin my friend.

I don't have to have proof to back this up but if you're interested in understanding why, here's a real good post on the subject

www.c2.com/.../wiki

Dave Schinkel wrote re: Is that a Property or a Method?
on 07-23-2009 11:06 AM

@Josh

My fault, I misread your post.  I thought you were talking about private fields and changing them to be public.  Disregard ;)

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)