Partial Methods – the most useless c# 3.0 feature?

I feel puzzled. On the one hand, I KNOW that Anders, Wes, and other people working on c# 3.0 language/compiler, are very smart people, yet I fail to see solid arguments why extend c# 3.0 with partial methods. Wes tried twice explain this feature, and I have read both posts twice, just to make sure I didn’t lose the gist of it.

To quote him:

Partial methods are methods that enable lightweight event handling.  Here is an example declaration:

partial class C

{

   static partial void M(int i);

}

The idea is that you have partial method declaration (notice the ‘;’ instead of {/*body*/}) and (optionally) implementation. If you don’t implement the partial method, all code that calls it will be removed during compilation. Since partial method MUST return void it seems pretty harmless. You don’t loose functionality and save several processor cycles.

All seems to be great, but let’s think of what you loose instead.

First and the most important: you loose code clarity.

Let’s say you wrote some code like this:

public partial class Class1

{

   public Class1()

   {

      partial void CurrentYear(ref int number);

      void DoSometiong()

      {

         int num = 0;

         CurrentYear(num);

         Console.WriteLine(num.ToString());

      }

   }

}

Big question: What will show up in the console? ‘0’? You are unable to tell! You’d have to find out wheatear the method was actually implemented or not. Since it would be probably in different file (what is reasonable – we’re dealing with partial classes here), and maintained by some other developer. If he/she forgot to implement this method you would not receive compilation time error (you probably would see warning but, it’s so easy not to notice them). If you don’t have tests to test this method you could ship broken app! This vagueness of code and potential source of errors is IMHO too high price for having several processor cycles saved. I would rather see it as a refactoring tool feature (removing private ‘OnEvents’ methods and events that never get called), rather than language element.

I guess that it will be one of those features that are there so that you could use them when you really need to but in 99 cases out of 100 you will not.

Technorati tags: , ,