A few time ago, one of my colleague has seen the following code

class UsingVariable
{
   private int myValue;
 
   public int MyValue
   {
      get { return myValue; }
      set { myValue = value; }
   }
 
   public UsingVariable()
   {
      // Let's set some default values
      myValue = 10;
   }
}

and proposed us to migrate it to that

class UsingAutoImplementedProperties
{
   public int MyValue { get; set; }
 
   public UsingAutoImplementedProperties()
   {
      // Let's set some default values
      MyValue = 10;
   }
}

argueing /explaining that now with the .NET 3.5 new features, it was possible, and as the local variable was not usefull, we could get rid of it.

When he told that I had a strongly opposed reaction. We should not do that. The local variable is not usefull ? And what about if the property was harmfull ? Let's see what could happen.

Comparison of the two codes:

Well nothing really to see. The code are currently perfectly equivalent. They will behave the same. Some purist may tell that the second is "slightly" slower (as using a call to property, ie to a method). Well... This is perfectly negligeable.

So these two codes are equivalent. I would precise : these two codes are equivalent... at the condition you assume your code will never get touched and changed in the future. And I'm not sure this is a bet an english bookmaker would do.

Let's see two possible evolutions and check what would happen.

Evolution 1 : some event raising in the property

You all know that for an auto-implemented property, both the get AND the set must be auto-implemented. As a consequence, if you need / want to do some extra treatment in one of the two, you will need to get rid of the auto-implementation to do it yourself. What could happen ? Let's imagine something like :

class UsingAutoImplementedProperties_Evolution1
{
   private int myValue;
 
   public int MyValue
   {
      get { return myValue; }
      set 
      {
         if ( myValue != value )
         {
            OnMyValueChanging(EventArgs.Empty);
            myValue = value;
            OnMyValueChanged(EventArgs.Empty);
         }
      }
   }
 
   //Other implementation ommited
}

We'll simply follow some .NET conventions to raise an event when the property has been changed. Well is that impossible ? Far from that I think.

What may happen ? Well, an event may be raised to indicate to a client that the internal state of the object has been changed. And the client may do some treatment on the object whose internal state has changed. Well yes but on which object really ? On that object I'm manipulating and on which I'm still not finished with the constructor ? Meaning on that object that may have any incorrect or un-initialized values ?

We can just smell there is something going wrong here.

Note that this case may not happen in real life. If I want to handle the event, I will need to have an instance no ? Right. Anyway, this example - not realistic but not so far from real life - let us smell and glimpse there may be some tricky problem to find out there.

Evolution 2 : Adding a level of hierarchy

Let's imagine we need to add a level of hierarchy in our class. We'll simply put for example the property as virtual.

class UsingAutoImplementedProperties_Evolution2
{
   public virtual int MyValue { get; set; }
   public UsingAutoImplementedProperties_Evolution2()
   {
      // Let's set some default values
      MyValue = 10;
   }
 
   //Other implementation ommited
}

And let's create any derived class, let's imagine like this.

class DerivedClass : UsingAutoImplementedProperties_Evolution2
{
   private OtherClass objectInitializedInCtor;
 
   public DerivedClass()
   {
      objectInitializedInCtor = new OtherClass();
   }
 
   public override int MyValue 
   {
      get { return base.MyValue; }
      set
      {
         objectInitializedInCtor.DoSomething();
         base.MyValue = value;
      }
   }
}

What is the consequence ? When I will do a new DerivedClass(), here is the workflow that will occur (I will simplify it by giving only the steps related to the code example) :

  • Initializing the variables of the class
    • Here, setting objectInitializedInCtor to null
  • Calling the constructor of the class
    • Meaning here doing nothing (for now) as we have a level of inheritance
  • Calling the need for building the base class
  • Initializing the variables of the base class
    • Here, setting the backing field of the MyValue property to 0
  • Calling the constructor of the class
    • Calling the property MyValue to set 10
    • This will in fine call the property MyValue of the derived class
    • This will call the method DoSomething on the objectInitializedInCtor (which is null)
    • This will crash 

This case is pretty simple as it will crash. Let's imagine now we are dealing with a collection that has been created, but not yet filled in, or on some values that still have their default value instead of the real one, this may cause very tricky bugs to find out.

Is that bad ? It's not my code...

What can we see here ? The application may crash / bug not because of the original code, but because of the evolutions we may bring to this code. The question may be "who is responsible for the bug ?".

Well in my view, the responsible is for sure the first code and NOT the evolution. Indeed we have assumed that our code WILL NOT evolve, and so we have put in place un-needed risks. And the guy making the evolution has just made a simple evolution, touching simply what he would need, and not more. I would even say, just what he was supposed to touch.

Imagining that the original code will not take this risk, is that defensive programmation ? Not in my view. For me defensive programmation is putting many things in place, because we thing the next one will add some bad / buggy code. Here it's the contrary, it's just writing the code to avoid having the next developper needing to think the ones before has written some bad / buggy code.

Does this resolve everything ?

No of course. But before detailing any other aspects related to the risky original code, or to the proposed code (ie without using properties in the constructor), I would like to listen to the reactions of all of you. To know what you think on the subject and which limitations you see.

As an architect, I like to regularly go back to the "basis" of development and to ask myself and others, again and again, the same architecture and conceptions questions. And each time, I discover new aspects and I succeed to understand better or deeper such or such domain.

In a previous post, I have spoken about my experience at the CITCON and my discovery of Open Space Discussions. I have found this concept very interesting and I have decided to use this concept for our architecture meetings. This concept will evolve about during our meetings.

This time, we'll meet on Monday December 17th at the Kaii Theater in Brussels to speak about nTiers development. This discussion will be led by Didier Pieroux, Dario Garcia Coder, Ronan Guillamet and myself. All topic can be aborded, but here are some ideas we were thinking to speak of :

  • Encapsulation
  • Separation of concerns
  • Data Access Layers, Persistence Layer and Stored Procedures
  • Value Objects and Business Objects
    • Inheritance
    • Composition
    • Conversion
    • What to expose and when

You would like to join ? Leave a comment and I will contact you !

EDIT: The meeting will start at 18h30 in "Les Halles St-Géry"

Hello All,

one of my colleague - Damien Pinauldt - has proposed us a small exercices yesterday. After I have seen the unexpected results, I have been thinking it could be interesting to share it with you.

The goal of this exercices was to recall how method hiding was working in .NET and what can be the consequences when using generics.

Method Hiding

Let's first redefine what is a method hiding. Of course you all know that in .NET are virtuals only the methods you decide to be, on the opposite of the Java World where all are virtual.
As a consequence, you may be in front of cases where you want to "override" a "non-virtual" method. We agree, this is highly unadviced and a bad practice. However you can, and you may face from time to time this obligation.

So you can be tempted to write something like this :

public class A
{
   public void DoSomething() { }
}
 
public class B : A
{
   public new void DoSomething() { }
}

And you would be right. This is an example of method hiding. In such a case, Visual Studio compiles without any error but gives you a warning explaining that there is a name collision inside of the classes A and B. By default, VS understands such a writing as "Method B.DoSomething is hiding inherited method A.DoSomething".
To clarify your (bad) intention (and get rid of this warning), you should use the "new" keyword:

public class B : A
{
  public new void DoSomething()  {}
} 

What is the consequence of such a code ?
Let's write an example and compare with polymorphism and method overriding:

public class A
{
   public void DoSomething() { Console.WriteLine("In A"); }
   public virtual void DoSomethingVirtual() { Console.WriteLine("In A"); }
} 
 
public class B : A
{
   public new void DoSomething() { Console.WriteLine("In B"); }
   public override void DoSomethingVirtual() { Console.WriteLine("In B"); }
} 

 

A a = new A();
a.DoSomething();           //Display "In A"
a.DoSomethingVirtual();    //Display "In A" 
 
B b = new B();
b.DoSomething();           //Display "In B"
b.DoSomethingVirtual();    //Display "In B" 
 
A a1 = new B();
a1.DoSomething();          //Display "In A"
a1.DoSomethingVirtual();   //Display "In B" 

In a word, the method resolution is based on the static type (meaning the type of the variable) when using method hiding, and is based on the dynamic type when using polymorphism and method overriding.
I imagine I didn't learned you anything here.

Generics and Generated IL

Ok now with theses basis recalled, let's go now to generics.
We often compare .NET generics with C++ templates and Java generics. In fact if the goal is quite similar, they work in very different ways.
To simplify, we could say .NET is at the mid-way between C++ and Java for code generation, avoiding the potential C++ "code bloating", and the Java "over casting". (You agree experts ?)
Is this better? Let's just say different.

.NET generics had been created to achieve two goals :

  • Improving the performance by avoiding the boxing and unboxing encountered when dealing with value types and "generic solution" (meaning here standard solutions, being applicable for many types, and so dealing with objects)
  • Ensure type safety

In my view, Microsoft as stated that they could deal with these two goals and had to face a choice that will anyway decrease a bit the performance:

  • either by generated a "huge" DLL (the typical code bloating due to some C++ compilers)
  • or by doing some casts

The final choice was:

  • We'll generate one new class / structure / method / ... for each ValueType using it
  • We'll generate only one class / structure / method / ... dealing with objects. A "compiler trick" can ensure type safety and give the illusion we work with strong typed solutions and doing some casts when appropriate

How can we verify that ? "Simply" by combining the method hiding and the generics (remember method hiding works with static types !)

Generics and method hiding

To avoid dealing with generic constraints (which won't anything by the way), let's create a simple method that will hide the ToString method and a simple generic method that will call the ToString().

public class C
{
   public new virtual string ToString()
   {
      return "In Class C";
   }
} 
 
public class Generic
{
   public static void DisplayToString<T>(T t)
   {
      Console.WriteLine(t.ToString());
   }
} 

This case is quite simple. So now let's compare what happens if we call the ToString method directly or via generics :

C c = new C();
object o = new C(); 
 
Console.WriteLine(c.ToString());    //Display "In Class C"
Console.WriteLine(o.ToString());    //Display "Namespace.C" 
 
Generic.DisplayToString(c);         //Display "Namespace.C"
Generic.DisplayToString(o);         //Display "Namespace.C"
Generic.DisplayToString<C>((C)o);   //Display "Namespace.C"

Why such a difference ? Simple, in fact when using the generic method, you are using one and only one method that takes an "object" and so the static type is "object".

Surprising ? Well I would say interesting :-) And definitely something to know if we are using some "new" keywords in our code. Maybe it would be another argument to avoid it ?

.NET has introduced since its very first version the concept of enumerations. It's of course quite nice and allow us to replace magic numbers in the code by self documented structure.

But their use is far over too common, without thinking before to the consequences of such a choice.
First people usually think that using an enum as a function parameter restrinct the range of the accepted values. Wrong.
We all know unfortunately that developpers use something without knowing all of it.
But this is not my main concern with enumerations.

Starting to use an enum will of course lead to some points in the code to conditional code, either using a "if / else" structure or a "switch" (please don't forget the default !). And this conditional code will soon start spreading all over the code.
And what happen if you had later on a new value to the enum ? You should check (and potentially update) the very numerous places where you have been using it to update acordingly the conditions to let it continue working with the new value.

OO and centralized code you have said ? No, no longer.


I won't discuss here more in detail this problematic as we have decided to hold an open discussion next tuesday (11th September 2007) either in Charleroi or in Brussels to address this specific point.
Interested in participating or in exchanging on this subject ? Please, leave a comment !

You probably create regularly new objects. Let's imagine you create a new class like this :

Of course you will use it and you will want in some moments to debug and see the value of your class. By default, here is what the debugger watch will show :

So of course, you know that the ToString method is used for the display and will update your object definition with non-fonctional - and probably not tested - code, to have a nicer debug display.

 

So you are now writing kind of debug code in your production environment. Definitely an error.
So let's remove the ToString method and let's achieve that differently !

And here it is ! Now your application contains only functional code and you can also have a nice debug experience !
Note that you can use the syntax "{name}" where "name" is either a internal member, a property, ... on which Visual Studio will call the ToString() method if necessary.

So to conclude, your application should never contain debug code. You may want to use the "ConditionalAttribute" or the "#if" syntax, but the best is not introduce debug code. And in such a case, the DebuggerDisplayAttribute is probably the solution that will perfectly suits your needs !