Field Vs. Property: Does It Really Matter?

Given my recent experiences with Ruby, my cursory knowledge of Java, and my past experiences with other object oriented systems, I find myself asking a lot of questions about why we do things the way we do in the C#/.NET space. Today’s questioning is about one of those fundamental things that I have been preaching for a long time, yet suddenly find myself unable to answer ‘why’:

field vs property: does it really matter?

As I sit and think about in the back of my head while writing code or this post, I can’t really say that I have any good reason for saying “you should use a property instead of a field” other than the defacto answer of encapsulation. But what if encapsulation doesn’t matter when you just want to store and retrieve a simple piece of data? Why is oh so important to use a property as the public API for a class?

Ruby doesn’t really have properties. It just has methods that allow you to use an = sign, but those methods are not even required to “set” a value. It’s only the conventional use of = methods that say you should. Java doesn’t have properties at all. It’s convention to use getWhatever and setWhatever methods, but it’s better design to not use mutators and I like the general reasons behind that.

So why does it matter if it’s a field vs. a property? Someone convince me that it’s important. Someone convince me that it’s not.  Better yet – someone explain the contexts in which it is important and the contexts in which it’s not, and someone point out where it’s important to hide the data behind the process through a mutator-less API of service methods.

Question everything – especially your own assumptions.


Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in .NET, Pragmatism, Principles and Patterns, Ruby. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://stevenharman.net Steven Harman

    three words: Representation Independent Code

    Gilad Bracha wrote about this back int 2007… http://gbracha.blogspot.com/2007/01/representation-independent-code.html

  • http://mynerditorium.blogspot.com Daniel Auger

    Philosophy aside – the .NET framework treats properties different than fields in scenarios such as databinding. That being the case, I tend to follow what the framework is expecting.

  • Ben

    The main reason I could think of off the top of my head is if you want to expose state as readable but writable only through a method (ala Mr. Laribee’s article that you linked).

    I’ve never like side-effect mutators… like a property called Salary where the setter validates a business rule and reacts accordingly. I’d rather that be done through a method….

    I mainly think it’s cargo cult programming. “I’d better use a property because otherwise I’m breaking encapsulation and the other programmers will laugh at me… ooo, look, I can do public MyField { get;set; }… I’ll pass code review now!”

  • Ben

    Counterpoint to my above statement… there’s seldom a reason not to use a property since it has nearly zero implementation overhead. public MyProperty { get; set; } and you’re done.

    as for contexts… given NHibernate

    class User {
    private IList roles = new List();

    public IEnumerable Roles { get { return roles; } }

    public void AddToRole(Role role) {}
    }

    Allowing someone to override your list on a loaded-from-NH user could cause some wonderful wackiness when you go to persist back. In many dev environments, this would be caught by unit testing, code review, pair programming, QA, or the fact that one person is writing it all so they won’t forget.

    Or, suppose you want to ‘enforce’ some state across entities (contrived here)… interface IAuditable { DateTime LastOpened { get; } }… you can’t do that with a field (ignoring that simply forcing state on an object doesn’t assure you of much…)

  • http://www.lostechies.com/members/jagregory/default.aspx James Gregory

    Two words: “private set”.

    Consistent state, immutable objects, always-valid objects, etc… Fields provide no access control and, without a true immutable object, make it dead easy to create objects in an invalid state.

    My question is: If it really doesn’t matter, why favour fields over properties? What does a public field get you that a public property doesn’t?

  • Brian

    When someone reflects over yer object & does GetProperty or GetField and you used the other, you’re pwnd.

  • J

    I’ll tend to use public members in classes where I just need to expose a bunch of information. Properties are more full featured (Read only, can be overridden for sub classes, and as someone above mentioned about the whole databinding thing in .NET) I think as anything if I need the functionality of properties I’ll go that route, but I’m just storing a bunch of data I’ll go with public fields.

  • dave-ilsw

    Generally speaking, if I’m just transporting data around, I use a field. If the data needs to be massaged, validated, or computed, then I use a property. Whether or not it’s important to use a field or a property depends entirely on your design and development context. Sometimes it matters. Sometimes it doesn’t.

  • http://melioratingmonkey.blogspot.com/ MM
  • http://kearon.blogspot.com Sean Kearon

    My convention is to prefer properties for “data that matters”. I know where to look when I want see the members that matter. I also use protected or private properties quite a lot when they are the “members that matter”.

  • http://melioratingmonkey.blogspot.com/ MM

    i think you’re doing a bit of apples v. oranges in parts of this post. you try to use the fact that java doesn’t have properties as an argument in favor of public fields in C#. but java’s lack of properties doesn’t mean that people then use public fields, it means, as you say, that they use get/set methods.

  • http://www.tobinharris.com Tobin Harris

    I use fields tons, because I’m lazy.

    public string Name;

    VS

    public string Name{get;set;}

    The first one is shorter. If I don’t need the good stuff a property brings to the table, why use it?

  • http://kevhunter.wordpress.com Kev Hunter

    I always use properties for exposing data, databinding, encapsulation, the ability to do INotifyPropertychanged and reflection as all valid reasons.

    Your probably using resharper so where’s the effort.

  • http://paulbatum.com Paul Batum

    Just wanted to +1 the link to Jon Skeet’s explanation
    http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx

    If we spend our brain cycles questioning the stuff that smart people have already thought about and answered, we’ve got less time for figuring out the stuff that has NOT already been answered. I say life’s too short to question absolutely everything. Gotta be pragmatic and take some things as a given :)

  • Michael Chandler

    It allows you a central place to set a breakpoint? :)

  • http://nolanegly.edgewolf.com Nolan Egly

    Hey Derick,

    I started to write out my thoughts on this, and ended publishing my first blog post. Congrats, two years after first encouraging me to blog you finally got me to write something :)

    http://nolanegly.edgewolf.com/content/fields-vs-properties-when-does-it-matter-when-it-preference

  • http://mikehadlow.blogspot.com/ Mike Hadlow

    Polymorphism? Or don’t we care about OO any more?

    Fields cannot be defined in interfaces, be declared virtual or overriden, so you can’t provide alternative implementations of any class where public fields provide the API. It pretty much rules out mocking or Dependency Injection.

  • http://mikenichols.devlicio.us Mike

    This depends on the context of your objects. In my domain, there had better be a real good reason for me to expose _any_ state. DTOs though may be safer to use properties since some frameworks handle these better or exclusively for serialization, proxying, etc…

  • AHZ

    For many of the reasons given above I prefer to use properties for any non-private members. That said, I think that the question is why is it that “public string Name {get; set; }” is any different than “public string Name;”? I personally feel like there should be no difference and if someone can explain why there should be a difference then that reason should answer your question.

  • http://melioratingmonkey.blogspot.com/ MM

    @AHZ, it’s no different “today”. but what if next year my requirements change and i need to do the following:

    private string name;
    public string Name
    {
    get
    {
    return name;
    }
    set
    {
    if (value == “Joey Joe Joe Junior Shabadoo”)
    {
    throw new ArgumentException(“That’s the worst name I ever heard!”);
    }
    else
    {
    name = value;
    }
    }
    }

    if i had just put forth the minuscule effort of using a property from the start, i don’t have to change code all over the place. i know you could argue YAGNI but i think YAGNI only applies when the “future proofing” effort is non-trivial.

  • http://adventuresinsoftware.com/blog Michael L Perry

    Absolutely it matters. Think about degrees of freedom (number of unknowns – number of equations). A field is an unknown, and therefore increases the degrees of freedom. A property does not.

    A property backed by a field (or an auto-implemented property) increases the degrees of freedom, because it has a field. But a property doesn’t have to be backed by a field. In these situations, it does not increase the degrees of freedom:

    * A property exposing an immutable constructor parameter.
    * A property referencing data in a related object.
    * A property performing calculations based on other fields/properties of the same object.

    Limiting the degrees of freedom in your code, you can reduce complexity and simplify testing. Properties can do that, but fields cannot.

  • http://blog.kellybrownsberger.com Kelly Brownsberger

    I’ve wondered this myself a few times. Generally speaking, I think the .NET community is so fragmented on application design patterns and principles. The use of properties vs. fields is one of the few things that we all follow more or less blindly. While it’s its always important to question things, I’m a little proud that at least we agree on this one across the board. It’s a start at least. Hopefully some other more value-add things make it into this category of “obeyed common-knowledge”.

    Having said that, I don’t think there’s a ton of value in properties over fields – especially for small apps that don’t change. But for other, more real world apps, there are differences (as others have pointed out).

    - The ability to make a setter as private is the big encapsulation factor in my book
    - The ability to implement things like INotifyPropertyChange
    - Fields and Properties are different things (look at System.Reflection – MemberInfo, FieldInfo, PropertyInfo) and can change the behavior of things like serialization and data binding.
    - Changing a field to a property or vice versa will force a recompile of consuming applications (not a small impact for the kind of applications I build).

    It sounds like maybe your really questioning whether C# needed both of these in general. You could probably make a good argument there. Now that we have them, I think we should continue to treat them as we have… but, again, probably not all that important to you, but there’s value is the ubiquitous best practice and the language has made so easy to follow, that I don’t know why you wouldn’t.

    My $0.02

  • http://geekswithblogs.net/technobabble Tom Besser

    The MSDN Design Guidelines cite versioning and security issues with fields that are overcome with properties.

    http://msdn.microsoft.com/en-us/library/ms229057(v=VS.90).aspx

    Chris Anderson also reveals that data binding only works with properties in the .NET Framework Design Guidelines, by Krzysztof Cwalina and Brad Abrams (2nd ed. p.161).

  • http://jarrettmeyer.com Jarrett

    XML serialization is automatic on properties with public getters and setters. Of course, you can also use [XmlInclude] if you really want to include a field.

  • http://www.lennybacon.com Daniel Fisher

    Reason #1: You cannot set a breakpoint on a field