web page hit counter

Sunday, September 18, 2005

The '#region' Directive in C# : Chocolate Covered Rat Turds Not Actually a Good Idea

Those of us who suffered through C and C++ preprocessor nightmares were happy to leave them behind when programming in Java. I was less than thrilled to get them back again in C#, but I try to keep an open mind.

One of the more interesting directives introduced with C# is '#region'. It's meant to make overlong source files filled with ugly methods look prettier to the casual browser. It comes in especially handy when hiding the large chunks of autogenerated code ('turds') produced when working with forms in Visual Studio.

Browsing through code with #region is a little like biting into chocolates from the "Whizzo Quality Assortment"[1]. No matter how pretty it looks, it's still a thin chocolate coating around crunchy raw unboned real dead frog bits.

If you sweep rotting pieces of implementation under the rug, then nobody is going to be cleaning them up, are they? If you make a 5000 line long source file look like it's 300 lines long by compressing up the view in outline mode, it's not actually 300 lines long, is it? If you shove your ugly method implementation under the couch cushions, then it doesn't magically become a good implementation, it's just a sticky surprise for the next person to reach under there looking for loose change.

To put it another way, imagine this: a novel that comes with #region directives so that you can avoid reading the badly written parts. Is that the sort of book you want to write?

Like preprocessor directives in C, there are legitimate uses for #region. Despite the title of this post, I was serious about covering up Visual Studio turds. It's not like you can do anything about them, and they're not meant to be hand-edited, so there's no deep harm in covering them up. And sometimes a badly written framework can force you to have dozens of boilerplate methods that nobody really needs to look at. But, overall, #region is a tool for people who'd rather hide their mistakes than clean them up. It should be avoided.

[1] "Ah - now, that's our speciality - covered with darkest creamy chocolate. When you pop it in your mouth steel bolts spring out and plunge straight through-both cheeks." - Monty Python "Crunchy Frog" sketch. After a couple of "Spring Surprises", people lean to avoid popping unfamiliar code into their mouth.

tags:blog, september, 2005, code, software, aesthetics, style, csharp, visualstudio, preprocessor, region

You should follow me on twitter here.


Anonymous Harris Reynolds said...

Fantastic stuff!! Love the analogy of looking for change!!


9:16 AM  
Blogger david said...

no doubt, I turn outlining off faster than one of my coworkers can tell me it's a "best practice."

Although I don't think these #regions affect compilation or have anything to do with preprocessor defs, I think they're just for VS.NET to interpret how it wants. (you didn't explicitly say they were preprocessed, just wanted to say that... ahem)

9:12 PM  
Blogger cks said...

Hmph, good point. #region is listed in the "Preprocessor Directives" section of the C# docs on MSDN, but it doesn't really act like one. On the other hand, the fact that #region can't overlap a #if block suggests that the C# preprocessing step does know about it. Really, #region is neither this nor that, which is another reason to dislike it :-)

11:47 AM  
Anonymous Anonymous said...

I put all my event handlers together, shared methods, etc., and collapse them into regions so that I can find where I'm going much quicker without scrolling through pages of code.

Just because you have drawers for your clothes doesn't mean your clothes are no good. Just means they're kept tidy until you need them.

Also, lots of code != bad code. Bad code == bad code, short or long.

5:41 AM  
Blogger cks said...

Code in a compilation unit is strongly coupled both by convention and the language definition. Lots of code in a single source file means lots of strongly coupled code. Sometimes the problem space requires this, but mostly it's just shoddy work.

6:49 AM  
Anonymous Dave Schinkel said...

Look, the point is:

1) Who wants to read that mess, if the code is a mess. Regions allow people to get in and see what's happening very quickly without getting their eyes glazed over with the mess you're talking about

2) If you are a coder, it's your responsibility to check out all the code. It's your responsibility to clean up. So by you saying that hiding using regions is going to prohibit someone from cleaning up bad code, the question should be why didn't management make that a standard across the team, and to take the initiative individually to help clean up any bad code based on some team standards!

You can turn them off, you can turn them on. The fact remains that the "bad" code isn't going to be changed even if it's in view, because of laziness and lack of standards in your culture.

You're point is not a good one, because regions are helpful...and it's the culture and individual who should be held responsible to standards across an organization a s a whole, so that the architecture remains a good one. This comes from top down, then individually...which is a problem in corporate america in many IT operations who just care about code and run & delivering to the user, not also maintaining a good architecture and standards across a programming team.

So, I support regions, as long as they are used appropriately meaning to segregate logical pieces in your code. They can save someone time, in reading other code during those so-called tight deadlines from top down ;)

11:24 AM  
Blogger &%%&$ said...

No doubt, #region is good for hiding mistakes, I was sweeping code to find a bug, when I find a very amusing method, with 2500 lines of code (and with 2500 lines of code, I’m being generous, cause I think that the method is larger), and the only logic break was the #region directive, I thought in suicide several times, but then I reengineer that method. #region should be used wisely.

7:51 AM  
Blogger artemis2020 said...

my prof sent the whole class some .CS files that contain #regions among other code.
He said we can use the code as a reference for the exam, during the exam. Now that I realize how bad #regions are, I have second thoughts on my professor's knowledge of #regions.

8:48 PM  
Blogger expresso said...

>>>I was sweeping code to find a bug, when I find a very amusing method, with 2500 lines of code (and with 2500 lines of code, I’m being generous, cause I think that the method is larger), and the only logic break was the #region directive

Once again, lame excuse NOT to use regions. Sorry, but these points are just dumb.

Regions organize code. If you have methods with 2500 lines of code, mabye your entire IT staff should be fired for doing so. Otherwise, you better be cleaning that up. Regions have nothing to do with this. You expand all regions when you look at a page of code anyway, they're called keyboard shortcuts, expand and collapse all regions or at least you know you're gonna expand the regions that you need to when you DEBUG? Has anyone ever turned on a debugger? That will expand the code for you as you step through. so what are you talking about "hiding". Hiding what? The proper way to find errors is to debug code in the first place in .NET!

7:19 PM  
Anonymous Anonymous said...

#regions are meant for easy browsing, if you are looking for mistakes it would be stupid not to "open" regions.

It's like a broken car and the mechanic does not open the hood to see what's going on...

9:45 AM  
Anonymous Anonymous said...

I wrap each method and property including their comments in regions so the entire file reads like the old c, c++ header file. Makes it simple to find out exactly where I need to go visually without having to search through everything. I don't however, like it when multiple methods get rolled up together, such as one region for all properties or all event handlers. I appear to be in the minority though.

12:29 PM  
Anonymous Aidan Hodges said...

I really cant see the issue with using regions to make it easier to browse through sections of Code - making it easier to find the infomation you are after, Although I do agree that using them to hide sections of bad code isn't a good idea.

To use the same analogy as the author, you wouldn't hide the badly written sections of a booking using regions - instead you'd break the book up into multiple sections to make reading the book easier (ie. chapters).

Regions shouldn't be used as a replacement for refactoring Code or breaking up methods. They should be used in conjunction to this in order to improve readablity by grouping up logical section of code making it easier to find.

10:31 PM  
Anonymous Anonymous said...

we are not goint to write any novel or story in Dot Net. Regions are made ot divide code logically, suppose we have to write a General code file which contains more then one functionality then you can divide the that part using regions. It has some logics to use and purely depends on how you see. In my opininon it's the best way for us to divide logically related code.

3:13 AM  
Anonymous Anonymous said...

I like regions a lot, and I do not consider my code messy.
Hey, I'm German, I very well suit the reputation that we love to organize everything and keep things tidy.
If somebody uses regions to hide bad code...well that's a lack of self discipline. Not using regions does not make your code any better. Using regions doesn't make it any worse...but it can make it much easier to read and navigate.

1:31 AM  
Blogger Tony said...

Dude, get off your big ugly horse. There are more reasons to use regions than covering up ugly code.

Its called organization, so when you are working within a team environment it is easy to keep pertinent sections etc....

Maybe you use regions to hid your turds but I have more professional uses for them.

1:26 AM  
OpenID mrchief said...

so by your own analogy, you must not have any closets, no dressers, no organizers of any kind, no cabinets or anything that remotely looks like a storage/organizing tool in your home; just four walls and piles (or may be flat) of stuff in the room lying there so that you can always look at them and 'maintain' them?

P.S. Above sentence intentionally kept long as probably breaking it up and organizing with punctuation is also chocolate covering I guess.

7:23 AM  

Post a Comment

<< Home