Public fields vs properties and a bit of YAGNI

Posted by Chris on February 24, 2007

A month ago or so a friend of mine IM:d me and said they were having a discussion regarding properties, if they should always be used to access fields or if you could sometimes just make the fields public. My response was instant (it was IM after all): *Always use properties*

Actually, even though I really think that “public fields should not even be allowed by the language”:http://gbracha.blogspot.com/2007/01/representation-independent-code.html, I confessed that I do sometimes use them in “test doubles”:http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html that I create for my unit tests (for instance for setting a value that I want some method to return when it is called in a test). But this is the only time I use public fields and I am trying to get away from it.

My friend did not agree with me and pointed me to “a post by Jeff Atwood”:http://www.codinghorror.com/blog/archives/000654.html. We did discuss this further that evening over a couple of beers, but I am not sure if I managed to persuade him. Probably not. :)

Some “other”:http://jimmynilsson.com/blog/posts/PropertiesVsFields.htm “smart”:http://blogs.msdn.com/ericgu/archive/2007/02/01/properties-vs-public-fields-redux.aspx “people”:http://blogs.msdn.com/jaybaz_ms/archive/2007/02/08/properties-vs-fields-again.aspx at least seem to agree with Jeff and my friend, but I do not buy into the arguments. It seems there are three main arguments given by proponents of public fields:

* *Performance*: Rico Mariani, performance guru at Microsoft, discusses performance differences between public fields and properties (as a part of a larger performance quiz on using value types for performance) in “two”:http://blogs.msdn.com/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx “posts”:http://blogs.msdn.com/ricom/archive/2006/09/07/performance-quiz-11-ten-questions-on-value-based-programming-solution.aspx. This is the only reason that I can actually sometimes accept. It is of course impossible to argument against it since the numbers are pretty clear, but in general most applications do not see any real difference from these issues. And if the language, and VM of course, did not even allow public fields I think more work could be done there to avoid problems.

* *Trivial properties are just meaningless wrapper code*: I really do not understand this argument. I guess these are the same people who name a variable of type Window to wnd instead of window, or a method that inserts a new value into some container to InsVal. Sure, silly examples, but my point is that typing is not really an issue with modern IDEs. Type prop and hit tab and you have got a property backed by a private field. More lines to read with properties? Sure, but seriously, how is that an issue? Personally I think the code is more readable and understandable with consistent use of properties for accessing an objects internals. And again, if the language did not allow public fields and instead had some syntactic sugar for easily creating properties backed by private fields, like @public property string Name;@, this would not even be an issue. C# 3.0 by the way seems to have something similar, as you can use @public string Name { get; set; }@ to accomplish this, although I think the previous one would be better.

* *Creating a trivial property is a premature decision because they will most often stay trivial forever*: I do not like this. Even if you think trivial properties makes it more difficult to understand the code, calling “YAGNI”:http://en.wikipedia.com/wiki/YAGNI on the decision to create one instead of using a public field to me is a misinterpretation or misuse of YAGNI. What it says that “you should defer making a decision until the *latest responsible moment*”, not simply “defer it until the latest possible moment”. What happens if you create a public field and then later change it into a property when it is used by clients? That is a “breaking change and clients will need to recompile from source”:http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx. Not a very responsible thing to do.

Even if I would agree with the above arguments, there are enough quirks and problems that you might get into from using public fields that I still recommend avoiding them. These include problems with parts of the .NET framework (databinding and reflection for instance), naming convention questions, and of course most importantly how changing from a public field to a property can break code in several ways, requiring recompiling from source. See the comments to Jeff Atwood’s post above (also summarized by himself in the updated part of the post), and the comments Eric Gunnerson’s post (summarized in a “follow-up post”:http://blogs.msdn.com/ericgu/archive/2007/02/02/more-on-properties-vs-fields.aspx) for more info.

Databinding a WPF control to something else than a static property

Posted by Chris on February 21, 2007

A couple of days ago I was trying to solve a problem with databinding in WPF. What I was trying to do was to create columns for a ListView (with a GridView set for it’s view). Creating columns was no problem, neither was binding the columns to some property of the objects in the list that was set as the ItemsSource of the ListView. The problem was however that the “properties” that I wanted to bind the columns to was not really properties (in the C#/.NET vocabulary).

To create a binding on a normal statically declared property, code like the below would work:

Binding binding = new Binding();
binding.Path = new PropertyPath("SomeProperty");
binding.Mode = BindingMode.OneWay;

FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
textElement.SetBinding(TextBlock.TextProperty, binding);

DataTemplate template = new DataTemplate();
template.VisualTree = textElement;

GridViewColumn column = new GridViewColumn();
column.CellTemplate = template;

With this code in place I now have a column containing a single textblock. The Text property of that textblock will contain the value of the property SomeProperty for each object in the collection that is set as the ItemsSource of the listview. However, as I mentioned above, the problem was that my object (or rather, the object’s type) did not have a static property called SomeProperty. Instead it has a property called Properties, which is a Dictionary containing a “dynamic” set of objects each representing some property (in the general meaning of the word, not in the C#/.NET vocabulary) of the object I am showing on the current row of the listview.

public class ShownInList {
  ...

  public Dictionary Properties {
    ...
  }
}

public class PropertyObject {
  ...

  public string Name {
    ...
  }

  public object Value {
    ...
  }
}

As seen above, each property has a name and a value. What I now want to do is to create a column and bind it to a property with a specific name, so that it will show the value of that property. The intuitive thing to try was to create the binding with a PropertyPath initialized with a string such as “Properties['SomeProperty']“. This did not work however, and neither did the different ways I tested to write the property path string.

Some Googling later I found the solution. Instead of binding to a property using a PropertyPath I could skip setting up the path at all and instead use a custom converter. Here is what I did:

Binding binding = new Binding();
binding.Converter = new PropertyObjectConverter();
binding.ConverterParameter = "SomeProperty";
binding.Mode = BindingMode.OneWay;

...

public class PropertyObjectConverter : IValueConverter {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
      ShownInList obj = (ShownInList)value;

      string key = (string)parameter;
      return obj.Properties.ContainsKey(key) ?
        obj.Properties[key].Value :
        null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
      throw new NotImplementedException();
    }
}

The binding is set up to call a converter to get a value to show. The converter is called with the object, of type ShownInList, that is the source for the current row, and a parameter describing which property in the dictionary I want to bind to. If the dictionary contains a propertyobject with the name as key then it returns the Value property of that object, otherwise it returns null.

If anyone has a better solution than mine then please add a comment about it.

Strange card games and methodology discussions

Posted by Chris on February 09, 2007

One of the most demoralizing and improductive things that can happen to a project and team are endless discussions about methodology.

Do not get me wrong here, how we work should definitely not be a once-and-for-all decision that we can never change. Quite the contrary, we must reflect regularly on the process and how we work, make changes as necessary and then follow up on those changes. But the point here is that we make these changes from some known base and we make them based on experiencing that something does not work for us. Most importantly changes are introduced at regular points in time (after an iteration), and we try them for some period of time long enough to be able to measure and decide whether they help us or not. What I am referring to with endless discussions about methodology is when a team starts out without having a process that they collectively agree upon and understand.


*Executive summary*: Before the start of a project, gather all the team members and collectively discuss and decide upon the process that the team will follow.


This reminds me of a card game we played in school at a class in Organizational/Group Theory (or something similar). The teacher started by telling us that starting now, *we were not allowed to talk to each other*. No oral communication whatsoever was allowed.

We were then divided into groups, I think there were five groups of five people each (but it’s not important). Each group were placed at a table that had a sheet of paper and a deck of cards. On the paper she had written down the rules for the card game we were going to play. Silently the paper was passed around between the five people at the table so that everyone knew the rules. I do not remember the rules exactly, but it was a very basic kind of “trick-taking game”:http://en.wikipedia.org/wiki/Trick-taking_game. The person who took the highest number of tricks was the winner.

When everyone at the table had read the rules she collected all the papers and told us to start playing. There were no “official” scoring (we had nothing to write on) so it was mostly for fun, but as always the winning instinct in people set in and we had a good time playing. Sometimes you would win a trick and throw your hands in the air in triumph, but noone was allowed to say anything or make any noise. After playing for a while we were stopped and *one person from each table were instructed to move counter-clockwise to the next table*.

Play then commenced again and everyone was happy. Until it happened for the first time that this new person and someone else reached for the trick to collect it at the same time. Confusion arose, the two “winners” looked at each other in anger (maybe not that much anger), and everyone wondered what was going one. Was this new guy trying to cheat? No talking was allowed, so after a while of looking and gesturing someone more or less just grabbed the trick and play continued. This problem was intensified when another person from each table was moved to a new one, this time clockwise. Now it was suddenly a very chaotic game of trick-taking with a lot of silent arguing going on. I think we switched one more time before we finished and discussed what had happened.

What did happen was of course that *each table started out with slightly different variations of the same rules*. When we were not allowed to discuss them then everyone, especially the “stronger” ones, just did things their way. Some “weaker” individuals just did not care and gave up their wins, even though they knew they had won, when someone else reached for the cards. I seem to remember that there were even someone who after figuring it out just started faking a win by reaching for the cards, bullying the others away from them.

The reason we did this exercise was to understand and experience the dynamics of team membership and disagreement. The strong natural leaders often came out winners while others did not win anything. But the reason I compare this with methodology discussions is the fact that we had different sets of base processes (rules) that we tried to follow. Sure, if we would have been allowed to talk about it I think we would eventually have decided upon some common rules that we could all follow. But the person that had to give up a trick that he thought he had won would not be happy, and the discussions would most likely be lengthy and tiresome. *What we should have done was of course to make sure that before we started the game everyone agreed upon the same rules*.

This is how it needs to be done in our projects as well. Before starting a new project a team should sit down and decide how they want to work, and make sure everyone commits to following the process decided upon. This might be as simple as saying “we will follow XP by the book” or you can go the Crystal way of deciding which practices to use. The important thing is that it is perfectly clear what is decided upon and that everyone commits to following it. Even if someone does not agree that a certain practice is a good one they should commit to following it if the team collectively decides to include it. After a couple of iterations the practice can be evaluated and changed if it did not work out. And this process of pinning down the methodology needs to be done *before the project starts*. Just like in the card game, having these discussions when everyone is busy doing Real Work^(TM)^ unfortunately guarantees that they will be lengthy and tiresome, and some people will get run over and feel bad about it.

*To sum up*: Before starting a project, make sure that everyone in the team understands and commits to the process the team is going to follow. But do not forget to reflect regularly and change the process as the team sees necessary.

Article about CLR integration posted

Posted by Chris on February 02, 2007

About a year ago I wrote an article for the “SQL Server Standard”:http://www.sqlserverstandard.com/ magazine called “Understanding CLR integration in SQL Server 2005″:/writings/understanding-clr-integration. This article is now also available here at my site, in the “Articles”:/writings section. It is an overview of how the CLR and SQL Server work together and tries to show how this is a much safer and better way to extend SQL Server than using extended stored procedures.