Home
  Latest posts
  My Writings
  My Code
  My Gallery
  About me
 
  rssfeed Syndication
 
Bloggtoppen.se
 
 
Links
  Cornerstone
  SweNug
 
Post categories
  misc (48)
  Architecture (21)
  C# (19)
  Asp.Net (2)
  Vb.Net (2)
  Training (7)
  Data (19)
  Events (40)
  Platform (2)
  Orcas (4)
  Updates (3)
  Methods (10)
  Tools (6)
  Announcements (14)
  Languages (1)
  Patterns (6)
  Opinions (11)
  Fun (3)
  Ineta (1)
  Opinion (0)
  Practices (2)
  WCF (5)
 
 
 

Encapsulation and Automatic properties in C# 3.0

Monday, September 10, 2007

C# 3.0 is just around the corner with all it's promises of glory and bridging between relational and OO semantics. In the after waves of the LINQ implementation a couple of cool new features are popping up. Some more cool then others (I still don't like the partial methods thingy, explained why here: http://www.lowendahl.net/showShout.aspx?id=132). When it comes to languages innovations for 3.0, just about every feature is implemented to support the LINQ scenarios. That is the case for automatic properties as well.

At first when I saw them I felt, "oh cool that will save me a lot of time". But then I thought about it and I'm not really that psyched any more and you can bet your retro gaming console that I will tell you why.

But first a short introduction to what automatic properties are. The idea is fairly simple, if you don't need any logic in your getters and setters you shouldn't really be forced to write them. This means that the syntax you have to write is quite simple:

public string Name { get; set; }

This just tells the compiler what you are after and the compiler will gladly generate the backing field and the code to write / read back and forth to the generated field. For a more technical description Bart de Smet has written an excellent post here: http://community.bartdesmet.net/blogs/bart/archive/2007/03/03/c-3-0-automatic-properties-explained.aspx

This is really convenient for another of the LINQ support features, anonymous types. When the types are generated they can utilize auto properties in the generation and voilá you got a class with properties.

Now the question is, does auto properties have any real value in any other scenario? I would argue that the answer to that question isn't technical but more about philosophy.

Before I make my argument I would like to explore the reasons why we encapsulate, for most it's something you do automatic. You've been pestered with the encapsulation mantra: "hide the access to the data so you can intercept the access or change how the data is stored". In most languages there are no native support for the encapsulation so you've often needed a special method like:

private string _name; public void setName(string value) {} public string getName() {}

This is usually added as a reflex since it's usually pretty hard to change from field access to set/get methods late in the project (a lot of search and replace if you don't got great tool support for it).

Since it's kind of a pain to add it later, encapsulation has been the thumb rule for a long time so long that I think Microsoft has forgotten about the reasons and by default reverted to "encapsulate everything" logic.

Encapsulating fields you don't need to hide right now is really a YAGNI violation. Very much so in C# and VB.NET. Since the syntax for accessing the get/set methods of an encapsulation is the same as reading/writing to a field we really don't have to worry about changing the implementation late in the project.

Can you (without intellisens) tell if this is a property or field:

currentCustomer.Name = "BillG";

Probably not. So if this is a field to begin with, it won't break any existing code to encapsulate it into a property later on.

Now back to automatic properties.

The idea is to simplify encapsulation, getters/setters, but it really misses the point. If I don't need interception, I don't need getters/setters. In that sense, automatic properties violates YAGNI. Since you can't access the backing field and you can't choose to make get or set automatic while implementing the other; automatic properties really don't bring more to the table then a public field would. (BTW, that is really a deal breaker for me, frameworks that access the field of a property for various reason will not be able to support automatic properties. Read Barts post for the details, hint: check the naming of the backing field)

So why are they there? Well since MS lives by the rule "encapsulate everything" it's frameworks can only work on properties. They have disqualified public fields as a viable way to read and write data to an object in their data binding solutions. As far as I know this is not a technical decision but a design decision, a design decision that breaks some of the most basic principles. It would be nice to get any comments from MS on the arguments behind this decision.

To sum up, I can understand where automatic properties comes from. It really simplifies encapsulation and developers don't have to write a lot of "dumb" encapsulation code just to support data binding and other features in the .NET Framework, but the idea that I needed to in the first place is really the issue here. .NET encapsulation is so similar to field access that the rule of "always encapsulate" is really out of date and MS should do something about their frameworks instead of inventing new language features.

kick it on DotNetKicks.com
 

Comments
9/10/2007 2:25:00 PM   http://www.codeassassin.com/   -   Jason Stangroome
 
Automatic Properties is a nice idea but I think I will rarely use them. Almost every property setter I've ever written does a null check and throws before assigning the new value to the private member. Automatic Properties doesn't seem to help with that.

Regards,
 
9/10/2007 3:18:00 PM   http://brennan.offwhite.net/blog/   -   Brennan Stehling
 
One benefit of using properties to wrap member variables is that an inheriting class can override their behavior. You can also use frameworks like Spring.NET which uses AOP to add behavior after your code has been compiled. You cannot use AOP with a simple member variable. But I try to avoid AOP. Where I have been considering using it lately is injecting behavior based on custom attributes so I can avoid writings lots of boilerplate code, like null checks. Then I can change the AOP implementation on place for the entire code base. Here is a good post on AOP.

http://www.ayende.com/Blog/archive/2007/07/02/7-Approaches-for-AOP-in-.Net.aspx
 
9/10/2007 3:55:00 PM   http://kirillosenkov.blogspot.com   -   Kirill Osenkov
 
Once you ship a field and the clients start relying on it, you can't change it to a property anymore.
A field cannot be an interface member.
You can't override fields in derived classes.
There might be complications with serialization and reflection (some tools extract only properties of a class using reflection).
So there are some good reasons even for default properties.
 
9/10/2007 4:36:00 PM   http://www.lowendahl.net   -   Patrik Löwendahl
 
Kirill, I'm not sure I agree with you that you can't change a field to a property after release. The syntax is the same and the access to the data is exaclty the same.

And yes there is reasons when you want to encapsulate, I'm not saying that properties are a bad thing. I'm just saying that defaulting to properties is bad practice and more often then not you don't need them (well expect for microsofts frameworks that can't work with anything else). Properly designed frameworks can work with both, look at NHibernate for example.
 
9/10/2007 5:52:00 PM     -   Jeremy Gray
 
Patrik - in your response to Kirill you are continuing to mistake syntax for compiled code, as you did when you wrote "So if this is a field to begin with, it won't break any existing code to encapsulate it into a property later on." in your article. If I ship an assembly with a public field, that fields needs to stay public in order to maintain back-compat, as best as I can tell.

If you are working in a scenario where you can ALWAYS recompile ALL of the code directly or indirectly dependent on that field, then by all means expose public fields all you like. All that does, however, is suggest that you are working on a very small project with a very small team that can afford a very lightweight versioning policy. Lucky you. :)
 
9/10/2007 6:02:00 PM   http://jdk.phpkid.org   -   JD
 
No, you can not change a public field to property afterwards. The reason is that Properties are actually method calls at IL level.

So even though syntax of accessing a public property and a public field is same, under the hood they differ and you can not substitute properties for public fields.

Read this:

http://kristofverbiest.blogspot.com/2007/02/public-fields-and-properties-are-not.html
 
9/10/2007 6:16:00 PM   http://www.lowendahl.net   -   Patrik Löwendahl
 
Well I'm actually assuming that you do recompile everything involved in a binary dependency scenario. And that doesn't have anything to do with small or big, it's just that in large scale applications I tend to have less binary dependencies.

Very short-sighted of me in my post, I was assuming that everyone was trying to move away from binary dependencies ;). Well my mistake.
 
9/10/2007 6:31:00 PM   http://jdk.phpkid.org   -   JD
 
Yep, depending on your situation binary compatibility may or may not matter. But it will be good idea if you append the post and include this information so that article is complete.
 
9/10/2007 9:30:00 PM     -   Daniel Gary
 
Let's remember that Visual Studio populates its property grid using a class's properties, not its public fields. So having automatic properties can save quite a bit of tedious work on a developer if they need their properties to be visible in the Property View.
 
9/12/2007 12:31:00 AM     -   [anonymous]
 
Yeah, I used to use public fields everywhere instead of writing a million stupid properties with no purpose. But most .NET developers freak out as this breaks some fundamental rule. I actually kind of understand their mindset as it seems once you start doing public variables everywhere, it makes things "feel" dirtier and may lead to other bad behaviors. But its purely an emotional response as opposed to a technical rational.

I like that they added this automatic property generator just to settle this issue. Also, plus its a nice way to do read only properties. (only get). In my experience, using immutable objects to pass data around tends to lead to a much easier to understand system.
 
10/10/2007 6:40:00 PM     -   Tor Haugen
 
No, Anonymous, it's not a nice way to do read only properties. Because without access to the auto-generated backing field they really would be read-only, and hence useless. I don't even think the compiler will allow it.

What the compiler will allow, however, is differentiated access to the getter and the setter. Public get / protected set is something I have been missing from C# since the beginning. With that feature in place, automatically generated properties become, at a stroke, way more useful than fields. Really.
 
3/20/2008 12:57:00 PM     -   Daniel
 
Say it altogeter, automatic properties is really bulshit.

1/ Very useless to do this :
public string FirstName
{
get; set;
}
//Instead DO a
public string FirstName;

2/ Auto prop MAY be usefull to protect the data initialization
public string FirstName
{
get; private set;
}
// No really Auto prop is very useless
// because all is already defined in .NET
public readonly FirstName

if some people have time to loss with auto prop, just go on with this bullshit.

 
3/28/2008 3:18:00 PM     -   Francesc
 
Daniel, I think saying a couple of times "bullshit" doesn't make you more right...
What you say in your first point will be always a very bad practice, it doesn't matter if you use automatic properties instead or not. If one day you need to add some checkings or operations when your field is accessed (like adding an OnPropertyChange event) you'll break all your client code.
In your second point, you compare apples and potatoes. A private setter doesn't make the property readonly. It will be always possible to change the value within the class. If it was readonly, the value stay the same for the life of the object. Again, using the properties you can always add extra processing without breaking the client code.
 
10/1/2008 8:00:00 PM   http://michaelgillson.com   -   Mike Gillson
 
Others have touched on this but there are some cases that an auto property is useful. The property is very much like a public field but I want to control the access to the setter. I only want the property to be changed by the base class.

public string SomeName { get; private set;}

Second, an interface can define a property but not a field. If the class implementing the interface really uses it as a property, than an auto property can be helpful.

I always struggled when I needed a simple field in class. Should I use camel case or pascal case in naming the field? Should I create a property with simple get/set? Now with auto properties, I just create an auto property.
 
2/8/2012 2:50:00 PM   http://www.basteln-selbermachen.de/   -   Mike
 
Hi, I won't start discussing if properties are useful, but I want to point out, that automatic properties are dangerous in combination with (binary) serialization:
If you use these auto props and not the full syntax with an explizit private member variable, the compile will generate a "backingField" - and store the content of the "property" in this field. If you need than later to write code for the getter or setter you need to create your own field. If you then deserialize older data from file ...
... you will get only the default values of the properties and cannot access your old data. :(


Comment
Title:
Your name:
Your url:
Text:
Please enter the text from the image: