Private methods vs. regions
Posted by Fernando Felman on March 8, 2007
Back in the days of VS2003 I had a discussion with a colleague regarding the usage of private methods vs. regions. You’re writing a long method (in our case it was a batch job activity) which will perform many actions / calculation one after the other. The question we were discussing is how to enclose the logical sections in that method, keeping in mind that each section will be executed only once.
My colleague (which from now will be called … hmmm… Adam!) supports the regions approach which means that every logical section is enclosed within a #region. In c# regions are collapsed by default and so when you review the main method code you’ve only to read the titles of the regions to understand what the method does. Should you want to inspect a logical section in more details, just open the region and you’re ready to go.
I supported the private methods approach which means that every logical section is enclosed in a private method. When you review the main method you only see the name of the methods (which should hint what the method does). Should you want to inspect a logical section in more details, you’ve to navigate to the relevant method’s definition.
There is no much difference between those two approaches: both support a way to enclose logical regions and both makes readable code. Adam said that since those methods doesn’t expose shared functionality and will only be called once, there is no reason to use them. At that time I couldn’t find a reason to why I prefer using private methods, expect that “it feels right”, and so we decided to just drop the whole subject.
But now that I’m using VS2005 I’ve a good reason for preferring the private methods approach: unit tests. In VS2005 you can generate unit tests and the great thing about it is that you can test private methods – VS will generate the appropriate code to access private methods via reflection. So if you enclose logical sections within private methods, you can automatically write tests to test only that functionality. But if you chose to enclose the logical sections using regions, there’s no way to automatically strip out just that functionality and expose it to the unit test.
What do you think – what approach would you choose for enclosing logical sections in long methods?