Saturday, March 3, 2012

C# regions are code smells

If you find yourself adding #regions to your code to make it easier to read and understand then this is a sign of a class that have gotten too big. Personally I prefer classes to be around 1 screen in height, and anything above this is less optimal and should be refactored.

How can you refactor away from using regions? There are 2 ways:
1) Split the class into many partial classes. This will make the class easier to read but not necessarily easier to understand or maintain.
2) Split the class into many smaller classes. The Single Responsibility Principle is important here, if the class only does one thing then it will be smaller, easier to read, understand and maintain.

Should you refactor to partial classes or smaller classes?
Try to refactor to smaller classes, and where this is not possible such as in public APIs or facade classes then refactor to partial classes.