Thursday, December 29, 2011

The Partial Class anti-pattern

In c# you can have a partial class.

This has a very specific function. It allows you to separate "Widget Generated Code" from the rest of your code. Then if you run the widget again, it won't overwrite all the additional code you have added. Think Windows Forms.

Of course when a class gets too large, you could* break up the class into multiple files, and use partial classes.

But this is very much brushing the problem under the rug.

Now you have made things worse.

If you have succeeded in breaking up the class into two or more partial classes which do not access private variables or private functions from the remainder of the partial class, then make it a brand new stand alone class.

If not, you now have a mini program within a large program, where you essentially have Global variables and functions  (albeit marked as private) which can be changed by code from another file. You can no longer see what is going on.

OK, in fairness you can use Resharper or some such tool to "find usages", but really you have just acknowledged the class was too big. Break it up into separate classes.


  • makes it more testable.
  • reduces the scope of private and protected members. 
  • may well separate out dependencies.
  • allows you to have higher level code in the primary class and hides the details of "the other stuff".

*if you do this, allow me to suggest that you don't go boasting about it to all your friends.

No comments:

Post a Comment