Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Properties vs. fields

I'm coming from a PHP/Java background and starting out learning C#/.NET. Properties as opposed to fields are one thing that baffles me -- or specifically, what advantages property accessors/mutators have over their method equivalents for fields.

MSDN has a great lecture series online about designing .NET class libraries here: http://msdn.microsoft.com/netframework/programming/classlibraries/default.aspx

It's aimed at framework authors, not application developers, but the general points it makes seem valid in both contexts.

The part titled "Member types" by Brad Abrams concernes the use of constructors, events, methods, fields and properties -- when and how to use each of them. I watched the presentation to see if it would clear my confusion, and to some extent it did, but not entirely.

Abrams says: "Properties are like smart fields, is what I call them.  They’re just a way to put some sugar around fields." That's what they've seemed like to me, as well.

He presents various conditions where properties and methods are appropriate. The gist of it seems to be that there are specific "requirements" (or at least strongly recommended best practices to avoid problems) for the use of properties:

- the getters should be simple and thus unlikely to throw exceptions
- they should not have dependencies on each other
- they should be settable in any order

Methods should be used when these preconditions are not met and/or when other circumstances make properties problematic (e.g. the order of setting matters, getters have possible side effects, returning an array, possible delayed return due to asynchronous operations etc.)

But what exactly is the compelling reason to use properties? Is there something beyond the syntactic sugar and the slightly smaller amount of typing required for property getters/setters as opposed to having similar methods for fields? It seems to me that fields can be used for everything that properties can, with the proper methods in place, if a little more cumbersomely.

Elamaton
Wednesday, March 23, 2005

"or specifically, what advantages property accessors/mutators have over their method equivalents"

Choose:

    javaObj.setValue(javaObj.getValue() + 5);

or

    dotnetObj.Value += 5;

There's a lot of value in simplifying the client code.

Brad Wilson (www.dotnetdevs.com)
Wednesday, March 23, 2005

Stick with the Properties. Properties allow you to hide the implementation and change the implementation with out changing a lot of code. The Properties act as an interface to the class. If you just use field names and change one you will have to change all the code that relies on that field name in the project. If you use Properties you can change the code that implements the Property and that is it as long as the Property name stays the same. In other words the change is only to the class that implements the Propery.

Hope this brain dump makes since...

TownDrunk
Wednesday, March 23, 2005

Just another source of info. for you to possibly peruse:

'Always Use Properties Instead of Accessible Data Members' is in fact the very first item (of 50) in Bill Wagners Effective C#.

I've learnt a lot from this book and haven't gotten nearly halfway yet - think it might be quite useful to you if you're coming to C# from Java - have a browse next time you're in a book store.

Gordon Hartley
Thursday, March 24, 2005

Some other benefits of properties.

1) Properties can be used easier through reflection to perform automated handling. For example, the property dialog editor is based on the concept of reflection against properties, not fields. You could technically do reflection against fields as well but the standard is to use properties.

2) Properties allow you to perform special processing when a value is set (or gotten). You can't do this with fields because there is no "hook" to put code in. For example, here is some C# code that will make sure a field is never null. You can't do this with fields.

public string FirstName
{
    set
    {
        if (value == null) value = "";
        this.firstName = value;
    }
}

3) Similar #3 above, properties give you a place to hook in events. I could easily add a method to invoke a FirstNameChanged event in the above setter. You can't do this with fields. This is probably the most important difference between using fields and properties.

matt
Thursday, March 24, 2005

In Java, you have the concept of a Bean.  All Beans are, as far as I can tell, are a poor substitute for properties.

Every public field must have a getter and setter method.  IMHO, properties keep it much cleaner.

The Java folks sometimes say, "but properties could be abused and the developer wouldn't know they're actually causing a very expensive operation instead of just setting/getting a value."  In practice, this scenario actually works *better* in .NET and Delphi than in Java.  In Java, developer are so used to using setters and getters that they treat them as inexpensive operations.  In .NET, the class designers generally use Properties for inexpensive set/get and functiosn for expensive set/get.  Therefore, developers using those classes are more wary of performance when using functions to set/get.

Properties can also make refactoring easier.  For example, pretend you originally had a PhoneNumber property that was just a string.  Later, the requirements change and you must track CountryCode and AreaCode seperately.  But of course there's a ton of code out there that uses the single PhoneNumber property.  So you change the PhoneNumber.Get to return a concatenated value of the CountryCode, AreaCode, and LocalPhoneDigits properties.  And you change the Set to parse the value and split it into the other properties.  Finally, you deprecate the PhoneNumber property with an ObsoleteAttribute, since it is now an expensive Set operation.

In a language without Properties, changing a field into set/get operations is always going to break old code.

Richard P
Friday, March 25, 2005

"In Java, developer are so used to using setters and getters that they treat them as inexpensive operations.  In .NET, the class designers generally use Properties for inexpensive set/get and functiosn for expensive set/get.  Therefore, developers using those classes are more wary of performance when using functions to set/get."

Ok, correct me if I'm wrong, but when you disassemble the IL of code containing a property, is it not converted to get_ and set_? Like with name:

public string Name
{
  get{return name;}
  set{name = value;}
}

becoming

public string get_Name
{
  return name;
}

public void set_Name
{
  name = value;
}

so I'm not sure why you would call those less expensive then a normal function/method call.

Cory Foy
Saturday, March 26, 2005

No, you're right, but he's talking about a _convention_.  He's not saying that properties are by their very nature lighter weight than methods, but rather that the convention is to use properties for lightweight operations and methods for expensive operations, especially if they have side effects.  For instance, using

object.Value

to get a simple value, but

object.GetValue()

if getting the value requires some calculations, database reads, etc.  The fact that a method is used draws attention to the fact that the operation is not lightweight.

Kyralessa
Saturday, March 26, 2005

Personally, I don't assume properites are quick, but that they are done in constant amortized time.

If you look at the source code to the underlying system (with something like Reflector), you'll see a very common pattern: exposing some data value that's expensive to calculate, via a property, usually resulted in a "calculation and cache" strategy. The first time you call, it may be expensive, but it is very cheap thereafter.

Brad Wilson [MSFT]
Monday, March 28, 2005

Another view:

http://www.devsource.com/article2/0,1759,1541911,00.asp

Bob
Wednesday, March 30, 2005

I'm glad to read someone else saying what I've suspected for quite a while, but have always been too chicken to actually start doing.

Of course, the next question is whether people will look down on me for using public variables instead of properties in my code.

But then I remember: I'm a VB programmer!  People already look down on me!  So, public variables it is.

Kyralessa
Wednesday, March 30, 2005

"I'm a VB programmer!  People already look down on me!  So, public variables it is."

And the wheel just keeps on turning. Sometimes I think VB programmers have it in their blood to make stupid decisions. Despite all that has been said here about the benefits of using properties, leave it to a VB programmer to ignore it all and take the advice of some two-bit hack with a blog. I think they all suffer from selective hearing.

matt
Wednesday, March 30, 2005

Did you actually _read_ that blog, matt?  Are you asserting that converting a public variable to a property will in fact break the interface?  Or what?  Yes, properties are great if you need to throw exceptions or do validation or raise events.  But if you don't, then what's the point when you can easily convert a public field to a property later anyway?

And also, don't be such a grump.

Kyralessa
Wednesday, March 30, 2005

Sorry Kyralessa... that was completely uncalled for. I apologize for being a grump. I need to take a break from these forums for a while. They get me too worked up.

Anyway... Yes, I read the article. I didn't see the ability to "change it later" as a very compelling argument. At least not enough to go against the standards. After all, you can always "change it later" no matter what road you take. That doesn't necessarily make it better in my mind.

Java doesn't have first class properties in the language. Instead, they use a crazy naming convention for methods to try and get similar functionality. If properties weren't useful then I doubt they would go to such trouble. I'm just glad that we have them in .NET.

Do whatever you think is best. I'm going to sign off for a while and take a vacation. I clearly need it.

matt
Thursday, March 31, 2005

Actually, changing from a field to a property IS a breaking change to the interface. It is re-compile compatible, but it does break anything that's compiled against the old code.

Brad Wilson [MSFT]
Sunday, April 03, 2005

"Actually, changing from a field to a property IS a breaking change to the interface. It is re-compile compatible, but it does break anything that's compiled against the old code. "

And it would break any code that uses reflection and assumes the value is a field. Changing it to a property requires you to actually have to change code as well.

matt
Monday, April 04, 2005

*  Recent Topics

*  Fog Creek Home