I <3 Steve McConnell*
Coding Horror
programming and human factors
by Jeff Atwood

July 06, 2008

The Problem With Code Folding

When you join a team, it's important to bend your preferences a little to accommodate the generally accepted coding practices of that team. Not everyone has to agree on every miniscule detail of the code, of course, but it's a good idea to dicuss it with your team and decide on overall approaches and philosophy beforehand. It promotes team harmony, and more than that, it's just common courtesy. As they say, when in Rome, do as the Romans do.

I've always been wary of cowboy coders who rolled into an ongoing project on fresh horses and immediately started dictating terms. It's a very short trip indeed from there to Who Wrote This Crap, and the predictable, inevitable finger-pointing at the foolhardy programmers who came before you begins. Don't be that guy or gal. Work with your team, not against it.

Still, there are some coding preferences people may feel.. strongly.. about. If that's the case, try to clear the air and address those strong preferences up front, as early as possible. Don't let them simmer. For me, the use of #region is one of those things. I tried to make myself clear in this twitter message:

Twitter message from codinghorror about #regions

So what is #region? It's a named hint you place in C# or VB.NET code to set a code folding point. Any code placed inside that region is, by default, collapsed when you re-open it in the editor. Here's a random example from the Log4Net project:

C# region example, log4net.Util.NativeError

Immediately I have a problem: I can't see anything! I have to manually expand those sections to browse any of the code in this class. It is possible to configure the Visual Studio IDE to not fold any of the regions when files are opened, but this is the out of box behavior, so that's what most developers will see. And of course there are keyboard shortcuts to deal with the regions:

Ctrl+M, Ctrl+M Collapse or expand the block you're currently in.
Ctrl+M, Ctrl+O Collapse all blocks in the file
Ctrl+M, Ctrl+L Expand all blocks in the file
Ctrl+M, Ctrl+P Stop outlining mode. (Ctrl+M, Ctrl+O resumes)

Here's the really sick part: once you expand the above log4net code there's literally three pages worth of code there! After you strip out all the massive XMLDoc comments and the dozen or so #region directives, you could have had all the code at your fingertips with a minor flick of the mouse wheel, in a simple scrollable layout.

I daresay being able to see the damn code is more important than having it meticulously segmented into six pointless little named buckets, but apparently a lot of programmers can't get enough of stuffing their code into pointless little named buckets. It's as if they've forgotten what the scroll bar -- and incremental search -- is for.

The #region directive drives me bonkers. It's not evil, per se, but I feel it is criminally overused in practice and heavily prone to abuse. I strongly urge you to think about how you're using code folding, because as I see it, there are a lot of downsides:

  1. Folding directives are glorified comments. #region has zero meaning to the compiler; it's a hint to the editor to allow code folding. It doesn't do any namespacing or scoping. Why, exactly, are we writing code to accommodate the editor? It boggles my mind that we'd add significant lines of code to our project that do nothing but offer organizational hints to the editor. Even traditional comments are a better value for your keystroke, because they can be more expressive. And folding is certainly no substitute at all for bona-fide refactoring.

  2. Folding is used to sweep code under the rug. Got a bunch of boring boilerplate code that makes your eyes water? A slew of ugly, gnarly code that nobody in their right mind wants to look at? Hide it in a region and fold that sucker into oblivion! Problem solved, right? Hardly. Your project is now full of crappy code that you can't see. That's worse. Much worse! Code that hides from you is code that will rot in the most putrescent and painful way possible. Your code should be front and center at all times -- exposed to as many programmers' eyes, and as much healing light, as possible.

  3. Folding is used to mask excessive length. The presence of folded code can lull developers into a false sense of what clean code looks like. Under the cover of folding, you can end up writing long, horrible spaghetti code blocks. If the code needs the crutch of folding to look organized, it's bad code.

  4. Folding can hide deficiencies in your editor. The presence of so-called "standard" boilerplate regions like "Public Constructors" and "Public Properties" and "Events" is not a feature. It's a bug. The editor should automatically offer to fold up these common structural blocks for you! I'm continually amazed that programmers spend time doing this scutwork when they could be writing useful code. Or at least demanding a smarter code editor.

I urge developers to write code that doesn't need folding to be readable, clear, and concise. I'm sure there are sane uses for code folding out there somewhere, but I rarely see them.

[advertisement] Peer code review without meetings, paperwork, or stopwatches? No wonder Code Collaborator won the Jolt Award.

Posted by Jeff Atwood    View blog reactions

 

« Investing in a Quality Programming Chair Spartan Programming »

 

Comments

'The editor should automatically offer to fold up these common structural blocks for you!' this sounds good, would you do this with a macro/plugin/other ?

sean on July 7, 2008 04:37 AM

Damn, I was just getting used to actually folding up the code. Thanks. Luckily, I'm new, so I can kick the habit if needed.

It does organize your code base. You don't really need to see all of your code at one given time. You don't need to flick the scroll wheel 20 times. If you're going into a source file to modify/add things, then open up the file, expand the area you want to add your code too, and you're done. Who cares about writing for the editors sake, it's for your own sanity.

But I understand your points. Code should be available for all to see, in the case that shitty code is written (it can easily be recognized). Plus, having it expanded gives you the opportunity for refinement when you're browsing down the file to write something and you notice you could have done something better.

David McGraw on July 7, 2008 04:44 AM

I guess there are differing approaches here. I'm working on a PHP module for Drupal at the moment, and my main file is ~2500 lines long. As I'm using Emacs, I split it up into sections delimited with a special comment beginning '///' (instead of the normal '//' it takes to begin a line comment in PHP), set outline-regexp to "^///" and use outline-minor-mode. This becomes an extremely light-weight form of folding (those section-delimiting comments would probably be there anyway) and makes the length manageable.

I guess your solution here would be to put each section, or a few closely linked sections, into a new file. This is feasible but I find it quicker to use folding compared to switching between different files.

David House on July 7, 2008 04:50 AM

> You don't really need to see all of your code at one given time. You don't need to flick the scroll wheel 20 times

Use CTRL+I incremental search. You only "see" what you find as you type.

> If you're going into a source file to modify/add things, then open up the file, expand the area you want to add your code too, and you're done.

If you're constantly editing one small area of a giant file, why isn't the part that changes frequently in a *different* file?

Jeff Atwood on July 7, 2008 04:50 AM

You mean you have to add something to code to accomplish this folding?

IntelliJ is an IDE that can manage by itself for Java. No additions to code necessary. And the foldings are open by default; you have to manually close them to get the code to disappear.

Maybe Visual Studio can learn something from IntelliJ.

JetBrain on July 7, 2008 04:58 AM

Now, this is interesting, because I tend to use #region more to HIDE THE CRAP (XML documentation etc, long list of attributes etc.) making it easier to see the important code..

I do tend to roll up the properties as well. Since 99% of the time the getters/setters aren't really doing much in themselves.

e.g.

#region Attributes
[Browsable(false)]
[MergableProperty(false)]
[DefaultValue(null)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(MyType))]
[TemplateInstance(TemplateInstance.Single)]
#endregion
public ITemplate ContentTemplate
{
get { return _temp; }
set { _temp = value; }
}

Becomes:

Attributes
public ITemplate ContentTemplate
{
get { return _temp; }
set { _temp = value; }
}

Much nicer :)

Rob on July 7, 2008 05:01 AM

I have to respectfully disagree. Regions are awesome. That's all I have to say on the matter.

Nick on July 7, 2008 05:04 AM

I too disagree. Like most newer language "features", if used properly they are indispensable for code organization. However, when used for the reasons you mention, they are certainly dangerous. Perhaps you just need to work with better coders... :)

For example, who needs to see all of the repetitive property accessors all the time. Just roll them up in a region and worry about looking at the non-trivial code.

Josh Anderson on July 7, 2008 05:09 AM

As ever I guess you've just managed to get yourself in just another conflicting topic.

I'm a big fan of code region, they actually help organizing my code. The fact that something can be over used where there's no need doesn't make it bad. You can put a comment on every single line of code so, should we stop using code comments since they can be potentially harmful?

Regions must be used when you can easily delimit aspects or functionality, they provide semantical separation into a unit. I prefer them (a lot) over partial classes.

If you have one constructor then DO NOT surround it with a region, but maybe you have 6 different constructors. In that case, surrounding them with a region allows for any developer to say "I don't really need to see the constructor code right now, let's take it out of the picture".

It is not about "protected region", "override regions" ... that might or might not be useful but I personally use them with things like "message processing methods" or "minor helpers" or "stream handling routines" and so on... It all dependes on what you're coding, if it is long enough but it must still be part of the same file then regions can help organizing the code in a semantical way.

I know the examples may be naive and there will be someone that will point out "you can put message methods in a different class and blah..." but in real projects some times just doesn't make sense to refactor a class to keep it size small at the prize of coupling increase or a more complex flow of messages between classes.

Jorge on July 7, 2008 05:10 AM

If the source file -needs- folding, there is a problem. Extract Class refactoring should be happening (accomplish hiding by design, not by editor directives).

The example file weighs in at ~300 lines. I don't think folding was required.

Wait a sec: 1/3 lines are public static methods? Doh!

David B on July 7, 2008 05:10 AM

The Eclipse IDE automatically manages code folding.

Niyaz PK on July 7, 2008 05:12 AM

I actually feel strongly enough about this one to comment.

I use the 'buckets' to hide a lot of rubbish in. Fortunately everyone in my team actually knows the Ctrl+M, Ctrl+L combo (Expand all blocks in the file).

I definitely see your point, but you should see the rubbish legacy code that we inherit (1000s of lines per class, sometimes even per method). First thing we do is put some regions in to allow the class to become browsable again.

Now, ideal - perfectly written - code should never need this, you are right. One day I hope to work in an environment that produces such code.

Jeroen Ritmeijer on July 7, 2008 05:12 AM

I actually feel strongly enough about this one to comment.

I use the 'buckets' to hide a lot of rubbish in. Fortunately everyone in my team actually knows the Ctrl+M, Ctrl+L combo (Expand all blocks in the file).

I definitely see your point, but you should see the rubbish legacy code that we inherit (1000s of lines per class, sometimes even per method). First thing we do is put some regions in to allow the class to become browsable again.

Now, ideal - perfectly written - code should never need this, you are right. One day I hope to work in an environment that produces such code.

Jeroen Ritmeijer on July 7, 2008 05:12 AM

There's a lot of things Visual Studio could do better if Microsoft bothered to copy the competition...

Paul on July 7, 2008 05:13 AM

I both agree and disagree with this post.

I used to be one of those who "regioned" everything. "Fields", "Constructors", "Properties", "Public Methods", etc. I thought I was doing something to organize the code. I knew where everything was, so it must be good! Only when I started seeing code like in your example (and even worse, when people *nest* the damned regions) did I realize my mistake. I was making regions that were good for *me*, and *nobody* else. It was how *I* organized the various parts of the code in my head, and most people had a tough time getting through it at first, if ever.

Still, I think regions can be good to hide large blocks of comments (as was previously mentioned) and I still ascribe to the Microsoft standard/default of putting a region around an interface implementation. That particular usage is common and frankly I've gotten used to it.

SpongeJim on July 7, 2008 05:13 AM

I think regions're fine if they're used properly.

snomag on July 7, 2008 05:14 AM

What's all the fuss about? If you don't like it why.. then you don't have to :)

Have to agree with people that in certain cases it makes code easier to maintain/read especially when you're dropping into code you didn't write yourself to fix bugs/add features.

If there is something that makes code unreadable/unmaintainable then it is partial classes! At least with #region you have all your code in the SAME FILE.

Sverrir on July 7, 2008 05:15 AM

> And the foldings are open by default; you have to manually close them to get the code to disappear.

In the base configuration, but you can set your IDE to auto-collapse by code block type (file headers, imports, javadoc comments, method bodies, annotations, getters&setters, inner classes, anonymous classes and xml tags)

Masklinn on July 7, 2008 05:19 AM

>> If you're constantly editing one small area of a giant file, why isn't the part that changes frequently in a *different* file?

If your changing one aspect all of the time, yeah you should put it in a different file.

But if you're adding new features, to, lets say, a game. You'll go into an input object to add something. Or you'll go into a graphics object to add something.

These are files that you would likely be modifying to add new features that wouldn't necessarily warrant a completely new class. Having those regions would save some strain on the fingers and the eyeballs.

>> Use CTRL+I incremental search. You only "see" what you find as you type.

I admit. I do need to use this more.

David McGraw on July 7, 2008 05:20 AM

Even though I strongly disagree, I feel these are great to organize code...it's nice to hear a differing view and we should be cautious so we don’t abuse them as in your example above.

Kevin on July 7, 2008 05:22 AM

I tend to find them nice, to organise like minded methods in the one section, especially with how we're doing unit tests at the moments against a repository pattern.

I tend to take the three or so tests for each method in that repository, and wrap them in #regions, specifically so the codebase remains small and navigatable without needing to be split into multiple files/classes/partial classes.

Plus, as you said, if it was a big issue there's Ctrl+M, Ctrl+L and all code blocks are expanded and you get the whole code again.

That said, VS also provides automatic blocks for you to collapse methods etc as need be.

*shrugs* I just find it nicer to group methods/tests that way and so I use it, YMMV as they say.

Andrew Tobin on July 7, 2008 05:23 AM

Yea, if you don't use them correctly than they're horrible.
I find the following use very nice though (as long as it is consistent across the source)

-Static Impl

-Fields

-Ctor

-Properties

-Public API

-Private Impl

It means you can easily burrow down to the kind of information you are looking for. All protected stuff ends up in Private Impl (which isn't pendantically correct but its purpose is to separate out the public (not subclass) entry points).

Jax on July 7, 2008 05:28 AM

Regions are just a hack to try to make up for Visual Studios ongoing complete lack of a decent code visualization tool.

By this I mean a dynamically updated (tree) view of the current source file that allows sorting, filtering and highlighting of code constructs such as namespaces, classes, methods, comments, fields properties etc.

I have tried a VS power toy that makes an attempt at this but it does not go far enough.

Microsoft continue to overlook basic programmer productivity features in favour of cool new headline features such as Linq, XAML designers etc. How about decent multi-monitor support in Visual Studio Microsoft?. It is 2008.

Sharp Develop seems to be improving all the time, maybe it will be the answer?

Ash on July 7, 2008 05:29 AM

Oh and:

- Nested types

(helper objects) at the bottom too. That usually covers everything.

Jax on July 7, 2008 05:30 AM

Sverrir:
"What's all the fuss about? If you don't like it why.. then you don't have to :)"

I think part of the fuss is inheriting it or working with a group where others do it - it's not always a case of "just not doing it", because someone else in your group will "just do it" ;)

Andrew Tobin on July 7, 2008 05:32 AM

dude, whats with the comment about terrorists?

Sameer Alibhai on July 7, 2008 05:35 AM

Let me start by acknowledging that you started this discussion by stating this is a "preference" not a fact and that you are entitled to your opinion.

That said, I believe the region directive is quite useful. All of your points can be easily addressed and some of them actually can be viewed as supporting rather than detracting from its use.

"Immediately I have a problem: I can't see anything!"
- So? When you enter a source file, how often do you really need to see everything, all at once. Can you really take all of that in? Besides, there is nothing to stop you from turning this off in your IDE like you said, but no amount of IDE configuration (currently) will add regions in for those who would like them.

"Here's the really sick part: once you expand the above log4net code there's literally three pages worth of code there!"
- This is a weak argument against regions and a strong one against cleaning up the Log4Net code. Showing an example of how a particular feature can be abused doesn't detract from it's usefulness, it simply demonstrates the need for some sanity and perhaps some "Best Practices" in its application.

"I daresay being able to see the damn code is more important than having it meticulously segmented into six pointless little named buckets, ... It's as if they've forgotten what the scroll bar -- and incremental search -- is for."
- Again, you can turn it off to have it all there if you wish and you can still use incremental search. Regions are not preventing you from using any of your favorite navigation methods. As you are well aware, there is more than one way to do things, and while you may favor one approach, others will have theirs.

"I strongly urge you to think about how you're using code folding, because as I see it, there are a lot of downsides: "
- Now we are getting into something more useful. Enumerating the ways this feature can be abused and working towards some "best practices" that the community at large can use to wisely apply it.

"It's a bug. The editor should automatically offer to fold up these common structural blocks for you!"
- I absolutely agree here. The editor *should* be more intelligent in providing these capabilities for you, negating most arguments in favor of #regions. However, saying that we shouldn't use the current "workaround" to provide the organization we want and should channel our energy into demanding a smarter editor is foolhearty. How many bugs, shortcomings, missing features, etc. are out there in the world in every piece of hardware, software, and everything-in-the-middle ware? If we demand perfection before moving forward, we would get no where.

"I urge developers to write code that doesn't need folding to be readable, clear, and concise. I'm sure there are sane uses for code folding out there somewhere, but I rarely see them."
- Again, I agree. Now that you have stated your views with the "team" and made it known that you do not negotiate with terrorists =], may I suggest a future article discussing best practices and common pitfalls of the region directive?

Thank you for the post (and the blog!). I believe these controversial ones are some of the most beneficial. What concerns me is when I see people blindly saying "oh this is bad? Thanks Jeff!" and running off without understanding the issues at hand and putting some thought of their own into it, but I digress..

Zach on July 7, 2008 05:39 AM

Regions are good for automatically generated code, not for much else.

Loz on July 7, 2008 05:41 AM

Jeff Atwood> If you're constantly editing one small area of a giant file, why isn't the part that changes frequently in a *different* file?

Placing part of the code into a different file has the same downsides as using '#region'. The only advantage one might gain is more granular and easier version control.

I think regions are not about hiding the code, they are about structuring your code. An IDE won't show you logical parts of your class.

Alexey Bobyakov on July 7, 2008 05:42 AM

Try jEdit. It's got some drawbacks but its code folding is far better -- it's on indents, not these awful regions

Derek Parnell on July 7, 2008 05:43 AM

"The editor should automatically offer to fold up these common structural blocks for you! I'm continually amazed that programmers spend time doing this scutwork when they could be writing useful code. Or at least demanding a smarter code editor."

Is there any way to make this work in Visual Studio? Which editor does that exactly, because I've never heard of an editor like that.

Daath on July 7, 2008 05:45 AM

LOL! Since when do you make such sweeping generalizations Jeff. Regions are good for some cases and bad for others. You take one case of where Regions are bad and apply it to everything. For Shame. Writing immaculate code is like the immaculate birth. IT NEVER HAPPENED!

Shawn Cook on July 7, 2008 05:45 AM

The trouble of incremental search is that it's only useful when you know exactly what, and the name of what are you looking for. Very often, I don't. Usually, I keep a visual idea of what the class looks like and what it does in my head. My mental representation of it isn't too far from what the Class Diagram in Visual Studio shows. When I want it to do something else, I open the file and *browse* through it to find what I want. Folding the code down helps tremendously in this.

Of course, you can question this approach to programming altogether. I'm guess I'm just not quite as hardcore as others. :)

Another reason for folding is because the summary XML Comments are tremendously verbose. For each one line it takes to declare a field, it takes three lines to describe it, at least in the OOB behavior. You end up with tons of "useful" clutter on screen which you can't chalk down to bad code; just to bad visualization.

Yet another example for folding, when you're trying to adhere to Microsoft's component model, you can often end up with something like this...

public event EventHandler SomethingChanged;

protected virtual void OnSomethingChanged( EventArgs e )
{
if ( Something != null )
Something( this, e );
}

Repeated 50 times for every OnPropertyChanged that you have on there. Even if you stick it at the end of the file, it's still mental overhead you can easily get rid of just by folding it down.

Ilia Jerebtsov on July 7, 2008 05:46 AM

I sometimes feel it useful to fold code at the entity level (class, method) but I really hate the profusion of #region in the c# code

For code browsing it is much easier to use a free-spinning-wheel mouse (like the Logitech VX) to cruise through the code and stop with a fingertip touch when needed.

Rui Gominho on July 7, 2008 05:48 AM

"I'm sure there are sane uses for code folding out there somewhere, but I rarely see them"

I agree, i've rarely seen regions used helpfully, visual studio will let you fold up methods quite happily, in most cases if your class has too many methods to fit, one per line, on the IDE then you have done something very very wrong.

Steve A on July 7, 2008 05:50 AM

Sameer Alibhai: "dude, whats with the comment about terrorists?"

I was wondering the same thing.

Arron on July 7, 2008 05:51 AM

Gotta disagree with you here. Code folding was (and still can be) a good thing.

Back In The Day, when "partial" classes weren't allowed and C# didn't have syntactical sugar for declaring get-only properties (oh, wait...) classes wound up with buttloads of code in them that was really just clutter and hid most of what was going on. #region was a good way of keeping all of that stuff out of my way.

It's not there for the compiler, it's there for *ME*.

Clinton Pierce on July 7, 2008 05:54 AM

I love #regions, but - just like yourself - think that coders use them to group constructors, methods, properties, etc. should be ritually and publicly shot in the town square immediately. ARGH!

I try to use them as sparingly as possible, but when I do, I love them. One example: real world class that has some feature, implemented with a public method/property and a number of private member variables and/or methods/properties. I then functionally group that functionality into one #region. When the region gets too big, it's a prime suspect for refactoring in a seperate class. Then they really add a lot.

But I agree that putting all your code in useless and often multiple #region subdivisions is about as evil as evil code gets! Too bad of an otherwise potentially great feature...

Jarno Peschier on July 7, 2008 05:56 AM

I hate it when you "implement the interface" in Visual studio and it auto-adds regions around the generated code. And when you add the interface and click it again, you get yet another region. Bad.

OmegaSupreme on July 7, 2008 05:57 AM

I usually agree with Jeff. I also like that he encourages and expects disagreement.

That said, I think this entry is somewhat shrill. I find #regions helpful in organizing code and allowing me to focus on particular sections. Any tool can be used irresponsibly, so I don't think #regions are necessarily appropriate, but I do like the idea that I can group functions together, that perhaps I don't wish to factor into a new class.

Rich Bateman on July 7, 2008 05:58 AM

Regions ROCK!!!!
Go back to vb6 and than you'll realize why we have regions.

Donny on July 7, 2008 05:58 AM

Code folding should be done by the IDE - It already understands the code so can fold it the same as it can highlight/colour/complete it ...

If your code is so long it needs folding to be manageable then you should not use folding ...

It is a nice feature to hide things that are currently not needed so you don't have to keep scrolling/searching around the code

The region directives if not understood by the compiler should not be in the code they are glorified comments

Jaster on July 7, 2008 05:59 AM

If you're using Intellisense, it un-collapses code. Unless I'm in the process of constructing the class, I very rarely go into a file without getting there from Intellisense.

Jarrett Meyer on July 7, 2008 06:01 AM

I used to not be a big fan of the regions; but used properly they can save you some time. If nothing else; if you need to scroll back and forth between some sections of code, by hiding code that you don't need to see it can make it a little easier.

I do agree with you that VS should have the ability to sort/group code based on protection type; similar to how it can sort using statements. On a similar note; I hate that VS can't create properties if you select more that one private member... why can it only do one at a time?

Gio on July 7, 2008 06:09 AM

#regions, used in moderation, are a useful organizing tool.

Jeff, next you'll be telling us how much you loathe chapters in books, or separate entries for blog posts, each comment in it's own block...

gunther on July 7, 2008 06:12 AM

I actually like code folding, it keeps un-necessary code out of sight and allows you to focus solely on the section you are interested in. folding on code blocks makes sense but some times say you have a class extending more than one interface (and this happens a lot) I find it really clever to be able to fold up implementations for distinct interfaces in distinct segments. If #regions are a waste of space, i think comments are an even greater waste. and to extend that logic, any coder worth his/her salt should be able to understand code and not need a comment. But of course some like me need it any way.

Sunil Dongre on July 7, 2008 06:13 AM

I think we all have seen the overuse of regions in codebases we maintain. I am in complete agreement that the automatic use of regions in every file is a code smell and should be avoided. Regions should be used just like comments, only when they make the code clearer or easier to read/understand.

For people looking to make their code more readable with regions I suggest reading Robert C. Martin new book Clean Code: A Handbook of Agile Software Craftsmanship. It is in rough cuts on O’Reilly Safari.

PS no regions necessary.

Adam Wolf on July 7, 2008 06:22 AM

Errr... I use regions in the VB.NET Express IDE and it does *NOT* automatically fold them closed every time I open up a file.

Is this perhaps only behavior found in Visual Studio Professional? Or is my computer just "charmed" to do things the right way?

Oh, and my $0.02 - I use regions, but sparingly, in classes. It's nice to be able to unfold just the particular section I'm after, and to fold related functions/declarations/etc. out of the way when I'm not using them. Especially when things get really long. The way the IDE shows folded code is visually distinct enough that I won't forget to "unfold" something. So, I find it helpful and useful, though I don't use it a lot.

Keithius on July 7, 2008 06:24 AM

>The editor should automatically offer to fold up these common structural blocks for you! I'm continually amazed that programmers spend time doing this scutwork when they could be writing useful code. Or at least demanding a smarter code editor.

>Microsoft doesn't negotiate with programmers! Buy VS 2008...suckers.


Joe Beam on July 7, 2008 06:27 AM

funny, i agree completly.

You have just forgotten one point. The standard search in Visual Studio does not search in hidden parts, like regions. (o.k. you can set a flag to search in hidden code, but that is not the standard behaviour, and i was very confused when a new programmer had changed "my" code and yust put regions in it after we worked 2 years completly without regions. I searched for something in "my" code and didn't find it in first place. Another 5 Minutes wasted when lookin why i can't find "my" code in "my" class. First looked in our source control system if anyone has changed names... and only seeing added region en masse.)

offler on July 7, 2008 06:29 AM

I'm going to have to disagree with you on this one Jeff.

In my experience it's been a very useful tool in the VS IDE. I'm not sure if any other editors support it, but it seems like you're railing against a feature of single (albeit major) IDE.

I think programming should be about elegant, efficient coding, using the syntactical structure of the chosen language. The #region tag is a tool useful for visual studio, but it means nothing to notepad. It does however still provide a visual cue as to what a certain block of code might do. Can it be abused? Sure, but with some discipline I believe it can be used to great effect.

Don't lose sight of what you're trying to accomplish and the code you're trying to write by getting caught up in the features of an IDE that as a whole can quickly become a crutch.

Dave on July 7, 2008 06:30 AM

I think I'm in agreement with Jeff, both about folding and about fitting in with your team. Unfortunately the team I joined likes code-folding.

I'm interested by the analogy with chapters in books. I guess all authors work differently, but I wonder if many start by writing out all their content in full and then deciding how to split it into separate chapters...? In my experience, that's the approach people take to code-folding.

Like most things available to us, I guess the relative merit of #region depends on how sensibly it's used.

For me, code-folding falls into the category of "things developers do when they're bored". Jeff - please write a post on "things developers do when they're bored" :-)

Martin on July 7, 2008 06:30 AM

You're getting all foamy over nothing. I would put it the other way around. I'm sure there are some INsane uses of folding, but I find it extremely useful to get where I want to go in a large source file. If it were used to fold up entire groups of structures or functions, OK, that would be stupid. However, it's much faster than scrolling through thousands of lines trying to visually scan for what I want, or hitting Ctrl-F and thinking up some phrase or variable that is in the approximate location of what I want.

I would think this would also help newcomers to a project (whom you just told to play nice! WTP!) get familiar with the overall structure of a source file.

Unfortunately for me (fortunate for you?) my work doesn't take me into visual studio very often.

Kwil on July 7, 2008 06:32 AM

Agreed. When I first saw code folding and the #region directive, I thought it was the coolest thing. After using it for a while, I realized maintaining the #region's costs time, and the increase in legibility is negligible. On top of that, visual studio by default does not search inside folded regions.

As an aside, XMLDoc's verbosity is the one reason why I don't use it. I prefer the JavaDoc syntax instead, which is a lot friendlier on human eyes. The slight loss of readability that comes with using JavaDoc is more than made up for by the very usable hyperlinked, cross-referenced HTML documentation I can generate from it.

Jeroen on July 7, 2008 06:38 AM

I use regions. Tell me I can't use regions and I'll get upset. Seriously, regions are great. There are instances where regions are very effective at organizing certain code sections and I find in those instances they add to readability significantly. I definitely don't use them where they are not needed. In fact, I don't really use them that often, but when I do they become a valuable organizational tool.

Let's please not do the "it's my way or it's wrong" kind of thing going. Since when was having options a bad thing. If you don't like a feature, then don't use it. If you don't like the fact that you have to crawl through someone else's code that uses regions, well, then that's too bad, but I'm sure you'll be able to cope. As you mention early in the post, you have to make some accommodations when you program as part of a team. Sure, the use of regions can be abused. Programmer's can abuse lot's of the tools available to them. Doesn't mean they shouldn't be allowed.

Come on, regions are not that big of a deal. Really.

kenneth on July 7, 2008 06:39 AM

@Jeff: "The presence of so-called "standard" boilerplate regions like "Public Constructors" and "Public Properties" and "Events" is not a feature. It's a bug."

Actually I'd go beyond that and say it is a failing of the language (at least in C#'s case).
To my mind a well-implemented class should be understandable purely from its public interface and associated comments. If you have to look inside a class to see what it does before you can use it then it is broken.

C# doesn't use 'header files', or public/private blocks, so it lacks that tangible separation between the public and private methods. Using a #regions for 'public methods', 'private methods' etc just lets you (poorly) simulate that concept.

(Some folk are bound to say that the solution to this is to write an Interface for each class and then code to that - which is fine in theory and often useful to some degree, but it does get very wearing. Instead I tend to refer to the Object Browser to ensure my public interface makes sense.)

Graham Stewart on July 7, 2008 06:40 AM

It all depends on how it is used. In the screenshot you used, the regions don't clearly tell me what to expand if I'm looking for a particular method or property. Where I work, we use regions to group similar methods and properties together, naming them approprietly does help a lot when looking for something.

I've seen it used excessively and it does get annoying because it adds no value, but when used correctly, it's a real benefit.

Mike B. on July 7, 2008 06:40 AM

Gotta disagree.
I like a small number of regions to help organize the code. With a second window and with Resharper I can keep a File Structure window open to help me navigate within the file.
If I open a file that's folded, a quick Ctl-M,Ctl-P opens it all up. No big.

Mark on July 7, 2008 06:41 AM

You can do code folding in Emacs, either using outline mode, or one of folding modes (extensions). But it is done *properly*, which means using specially crafted comments, for example
/* {{{ Public Static Methods */
...
/* }}} */
where, of course, choice of comment markers depend on the programming language used. Using comments has the additional advantage of being useful even when all blocks are expanded. Also, it is not on by default.

As to navigating the code: incremental search and named or per file bookmarks are much better solution.

Jakub Narębski on July 7, 2008 06:41 AM

One obvious failing of the Visual Studio editor is that it doesn't indicate which region(s) your cursor is currently in.

If it was displayed on the status bar then it might help prevent the situation where say, event handler methods get added outside the #region "Event Handlers".

Even better would be if there were standard enforceable regions that could be checked by the compiler - so that if you use the standard #region "Public Methods" then it warns you if you add a public method outside that region.

Though ultimately, as Jeff says, the best solution would be that the editor just recognised such groups of methods and did the grouping for you without help.

Graham Stewart on July 7, 2008 06:50 AM

Great post Jeff

I don't mind the odd region here or there to logically group stuff together, but I really dislike the convention of putting things in regions according to accessibility. Here's my own rant on this from a year ago...
http://mark-dot-net.blogspot.com/2007/06/visual-studio-regions.html

and thanks for the Ctrl-I incremental search tip. I didn't even know that feature was in there

Mark on July 7, 2008 06:50 AM

Some features are useful in the right hands, but frequently improperly used, or overused. "Hungarian Notation" would be a great example. You can use it to embed semantic information about otherwise-interchangeable C pointers, or you can use it to make your code pointlessly unreadable. Looks like we can add another feature to that category.

A. Lloyd Flanagan on July 7, 2008 06:54 AM

I'm not a big fan of #region. But I use them and find them more practical than extensive creation of partial files.

However, I agree with you that the editor should automatically offer to fold up common structural blocks for you. It should also collapse XMLDoc comments by default, maybe attributes too.

Hinek on July 7, 2008 06:57 AM

If you are using VS08 (and I believe it's in VS05 too), you can force the IDE to open in expanded mode. Therefore you 'll get your "unfolded" appearance you are looking for.

Tools|Options then Text Editor, C#, Advanced and Outlining, Enter Outlining mode when files open.

I know, I know, it's not perfect for you, but it does help you blend in with your team a bit more without the CTRL M + CTRL L

PHenry on July 7, 2008 06:58 AM

So Jeff, do you use XMLDoc comments? I've used them for a library I wrote that I thought might end up being public and I hate them. They clutter up the code so much. Do you think it's bad form to stick with standard comments for internal projects where you don't really need a help document?

Ben Mills on July 7, 2008 06:58 AM


"Regions are great for organising my code" sounds like a code smell to me. Your code ought to be organised already.

That said, C# and VB suffer (as do C++ and Java) from having all the code inline. Languages like Delphi, Modula2 etc that had separate sections to define the interface (in the sense of signature) of a class make code folding redundant.

If the code would fold with one click to give you a nice clean definition, that would perhaps make it worthwhile. But it doesn't. Particularly if you have regions within your class.

Jim Cooper on July 7, 2008 07:04 AM

Dang Jeff you've gone crazy again :-) Regions are awesome for hiding dumb insignificant code while you concentrate on the crap code that has generated 37,000 different support calls. It certainly helps me concentrate. It's really a question of if they're being overused/abused in the codebase.

o.s. on July 7, 2008 07:08 AM

I'll lend you a battlecruiser for your war, Jeff.

Regions are almost always a completely abused waste of time. Each person is inventing new uses for regions (almost always duplicating the basic functionality of the IDE. Regions for private / public / etc, are asinine and redundant, but *worse* still they encourage the developer to segregate these items even when the code would be clearer if they were all together).

Dennis Forbes on July 7, 2008 07:09 AM

I'm with you on regions, so often I've seen a region inside a class containing a nice chunk of related self-contained code that should really be an inner class. It's a way for people to write procedural code inside a class. If you find yourself wanting to add a #region you should really look at your class and ask this question.

Do I have any functionality here that would be better split into an extra class?

I think most regions in code can be removed and replaced with better code structure

David Hayes on July 7, 2008 07:09 AM

I'm guessing that Regions originally started as a way to hide all the auto-generated code from Winforms, since that's where I first saw it. Then gradually the practice of using it to reduce a long classes into sections of methods, stubs, private data, etc, became popular from watching c# and vb demo videos and sample code. Still this type of sorting is a real need. Comments, annotations, and coding styles are all to help readability and with intent. I still think IDEs have a long way to go with helping programmers record intent and express conditions.

Ben L on July 7, 2008 07:17 AM

@Jeff

Or in a different class.

Totally agree, regions cause friction.

Resharper can help with that btw.

Matt on July 7, 2008 07:18 AM

Used correctly, code folding HELPS you see code. In this scenario, it hides those three ugly pages of logging code so that you can see the code that matters. If you want to see everything, it's an easy Ctrl+M, Ctrl+L.

JS on July 7, 2008 07:19 AM

Jeff,

100% agree. #regions blow.

Might as well have called it

#rugwithdustunderneath
#loadedgun
#tomaximizeyourcodingtimeandeffortlookherelast

John Pirie on July 7, 2008 07:22 AM

"It is possible to configure the Visual Studio IDE to not fold any of the regions when files are opened, but this is the out of box behavior, so that's what most developers will see."

Well there you have it then. You set up your VS like that and you start working. There, wasn't that easy?

Mike on July 7, 2008 07:23 AM

Heh. I haven't used .NET stuff before. I have to say that I don't find it a good sign when a laguage has a "Jedi-mind trick" primitive.

These are not the lines of code you are looking for. (*waves hand*) They can go about their business. (*waves hand*) Move along.

T.E.D. on July 7, 2008 07:26 AM

"It boggles my mind that we'd add significant lines of code to our project that do nothing but offer organizational hints to the editor."

Spoken like a true zealot. If the amount is significant, than you must have 10 lines of code overall.

Mike on July 7, 2008 07:27 AM

"The editor should automatically offer to fold up these common structural blocks for you!"

Whaa? So folding IS good?

I have found 3 problems in your argument, and I must come to the conclusion that you are writing this for the views. Well, you have to make a living so do what you feel you need to do, but you are out of my rss reader sir.

Mike on July 7, 2008 07:30 AM

Having to actually put something in your code to support folding sounds brain-dead to me. I use TextMate, and it handles folding automatically, at various levels. I use it mostly with specs, since I often want to see the specs rather than the code that verifies them.
i.e.
describe MyClass do
it "should do something" do
(...folded)

it "should do something else" do
(...folded)

describe "when doing something" do
it "should keep track of foos" do
end

describe "when not doing something" do
(...folded)
end

And it is nice that it remembers exactly how I had the code folded when I last closed the file, without me having to insert a bunch of stuff into my source code.

Matt V on July 7, 2008 07:30 AM

Code folding is a useful feature. It was bad enough having to strum my mouse wheel 20 times to get to this input box... (please do something about that :) ) doing it in a code editor when I'm trying to remember complicated constructs is worse. Take me, quickly, to the source I want, and then don't confuse me with lots of clutter I don't want to see.

Boilerplate code is stuff we never edit, so we don't need to look at it.

> There's a lot of things Visual Studio could do better if Microsoft bothered to copy the competition...

And there's a lot of things they've done very very Right.

Go use Eclipse, XCode or KDEvelop ;)

James on July 7, 2008 07:31 AM

Automatic folding? Use VIM. :)

Bruno Nery on July 7, 2008 07:31 AM

I fail to see the problem. You say that you can configure your IDE to expand all by default, so why not just setting this one option and live happy? If other programmers prefer to have these collapsed, why forcing your way upon them if there's an easy way to workaround it?

Mecki on July 7, 2008 07:35 AM

First of all a lot of people are getting the impression that the only way the VS IDE will do code folding is with regions. This is not the case and the post is inappropriately titled because Jeff seems to only have a problem with the region directive.

Frankly its an opinion not fact. If you don't want to use regions you don't have to, if I want to use regions I will whether or not Jeff Atwood likes them.

Matt Newman on July 7, 2008 07:44 AM

If learning to live with #regions in Visual Studio, I recommend changing the background colour for preprocessor directives. This makes #region markers stand out well as you scroll past them.

I also strongly recommend getting a mouse with a flywheel-style scroll wheel. I got a Logitech VX Nano for my laptop and now I use it with my desktop whenever I can. It makes it much easier to scroll through long source files or other documents. With a flick you can send the wheel spinning to scroll quickly through even very long files, while you still have fine control when you need it.

Weeble on July 7, 2008 07:45 AM

"#region has zero meaning to the compiler; it's a hint to the editor to allow code folding. It doesn't do any namespacing or scoping. Why, exactly, are we writing code to accommodate the editor?"

I *strongly* agree. And in the same way: "type declarations add zero meaning to the program logic; it's a hint to the compiler. Why exactly are we writing code to accomodate the compiler that adds nothing to the program" (except to prevent you doing all sorts of stuff...).

Michael Foord on July 7, 2008 07:57 AM

The suggestion to "simplify" one's code by splitting it into to several partial classes is laughable. Partial classes came about purely as a result of the way Visual Studio's form designer works. Otherwise they're a terrible idea IMHO.

PS. Visual Studio doesn't require "having to actually put something in your code to support folding".

Rhywun on July 7, 2008 07:58 AM

Where do you see the difference between folding and using different files for different classes ? Both hides lots of codes behind short identifiers, so you don't always have to look at everything at once.

Also: you are welcome to set your IDE to auto expand. Bam!, problem solved for you. You will never ever be bugged by those hidden pieces of code again. Other people on your team, however, do not have an easy way to fold the code away if they wish to do so and you removed all the #region's. Clearly, no #region's hurt part of the team, and lots of #regions don't really hurt anyone (since you can just set your IDE to auto expand if you don't like them). The choice is absolutely obvious.

J. Stoever on July 7, 2008 07:58 AM

Jeff, you've been reading my blog again!

"No to #region"
http://mikehadlow.blogspot.com/2006/10/no-to-region.html

Mike Hadlow on July 7, 2008 08:04 AM

Hmm... I have the answer, never use C#. There is no reason for it to exist. As for regions in VB, well VB is so verbose you need regions just to find your code.
I must admit to being a Java coder, so I have biases. I will have to say that I wish that Java had an answer to VS2008. Eclipse sucks, NetBeans makes the programmer code the way it wants you to code, and JBuilder's libraries are out of date. So while MS languages are horrid, their IDE is still better than anyone else. Go TextPad.

Mark on July 7, 2008 08:05 AM

Ctrl-M Ctrl-P

What are you, George Jetson? Waaah, Jane, my fingers hurt from pressing 2 buttons.

Or just turn it off in your IDE.

Seriously, call the Wahbulance.

Everyone thinks differently and I'm sure it really helps other people have a framework to get organized. Do I think people should group methods by private and public? No. But I'm not going to write a whiny blog post about it. (I just hit Ctrl-M Ctrl-P and it all goes away...)

And it beats the heck off 100 separate partial class files. Yuck! And there's no way for people that don't like that to fix it.

PRMan on July 7, 2008 08:07 AM

What's so great about not organizing your code? I mean, I want my programming job to be easier, faster and keep me as much as possible from making stupid mistakes.

Also, there are reasons for being nice to the editor. In fact, I think being editor-friendly is a FEATURE of a language. For example, in C++ it's often hard to figure out where an actual ERROR is, because of an unclosed quote and the semicolons might be all messed up for a long time down. But if line breaks ALSO end a statement, your development time will be quicker over time.

Gregory Magarshak on July 7, 2008 08:07 AM

Holy cow. Talk about short sighted.

You don't organize code? Really? You don't place functions and procedures together that all relate in your source files?

Folding has a place and I'm very surprised that you don't see that.

There are a lot of times that we have HAD to use that #Region just so that we can easily find things. You try searching a large file for a word that gets repeated 50 times throughout the whole class file... As soon as we started using #Regions properly, life was MUCH easier and WAY more efficient.

Aaron on July 7, 2008 08:07 AM

I'll agree with the other folks here, regions are awsome. Sure, they can be overused (regions within regions within regions). Normally when I open a class, I want to go to a specific part of it. It is rare that I want to see properties and private fields, but when I do typically I don't want to see the methods. And it is only once in a very long time I want to see my references.

Regions make it so that is handled pretty elegantly.

Matt Briggs on July 7, 2008 08:08 AM

I think Jeff is wrong on this one. #region is very handy.

In addition, the IDE will fold code on any block level statement, not just regions.

Jonathan Holland on July 7, 2008 08:09 AM

Here is the problem with regions.

When I open up a file in VS, I usually want to see collapsed code, like this:

public string AddressLine1[...]

public string AddressLine2[...]

etc.

I have keyboard shortcuts for the various outlining commands: Alt-Right to expand/collapse all, Alt-Left to CollapseToDefinitions, and Alt-Down to toggle outlining open/closed for the block I'm in.

But regions completely screw up outlining. If I expand everything, I get this:

#region Properties

public string AddressLine1
{
get { return addressLine1; }
set { addressLine1 = value; }
}

public string AddressLine2
{
get { return addressLine2; }
set { addressLine2 = value; }
}

etc.

Too verbose. Whereas if I collapse to definitions, I get this:

Properties

Now I can't see anything. So to get a collapsed view of all the code, I have to collapse everything, then individually open each region, which is an annoying waste of time.

It's easy enough to group things in terms of methods, event handlers, properties, etc. with comments. We don't need to use regions to do it.

Regions should only be used for boilerplate code that doesn't ordinarily need to be seen. Designer code is one example of this. C# event declarations (as someone referred to above) is potentially another. Any code that regularly needs to be edited, or that one needs to be aware of when adding to a class, should not be in regions.

Kyralessa on July 7, 2008 08:13 AM

This is too funny --- I often find myself reading Jeff's stuff and trying to decide if he's right and I'm just old and crotchety about the way code "should be" (80 char width, hungarian notation, intellisense is the crutch of the weak, etc.) ... today I got to see Jeff turn the corner into old and crotchety too.

Hey you kids, get out of my yard!

---S

Sean on July 7, 2008 08:13 AM

If you don't like using #region then don't use it. It's purely a personal preference thing. What I hate is empty regions. You end up clicking on all these regions trying to find the method you need.

Steven Rogers on July 7, 2008 08:15 AM

'Folding can hide deficiencies in your editor. The presence of so-called "standard" boilerplate regions like "Public Constructors" and "Public Properties" and "Events" is not a feature. It's a bug. The editor should automatically offer to fold up these common structural blocks for you! I'm continually amazed that programmers spend time doing this scutwork when they could be writing useful code. Or at least demanding a smarter code editor.'

Folding can hide deficiencies in your editor, while your editor can hide deficiencies in your *language*. I am frequently annoyed when C# (or C++, or Java) requires lots of ugly boilerplate code. Any time I find myself writing the same pattern of code several times I start looking for ways to avoid the duplication, but often I get to a point where it comes down to fundamental limits of the language. Perhaps I would be happier writing Lisp.

Weeble on July 7, 2008 08:15 AM

@James:

>> It was bad enough having to strum my mouse wheel 20 times to get to this input box... (please do something about that :) )

I fixed this problem for you. Next time you want to jump right to the input box, just press the 'End' key. You might have to clear your browser cache for this fix to get downloaded to your machine.

stevey on July 7, 2008 08:15 AM

> There are a lot of times that we have HAD to use that #Region just
> so that we can easily find things. You try searching a large file

I don't have your code in front of me so I can't really make any judgements. However, I've found over the years that if a file gets really large, tough to navigate around, and/or tough to read, it almost always needs some funtionality split out of it and put into another file/class.

My suggestion for users of this #Region thingy would be to instead physically take that code you want to hide out and put it somewhere else.

T.E.D. on July 7, 2008 08:17 AM

I agree that #regions are a bad thing when overused, and especially hard to navigate when there are nested #regions. But for very simple code organization, I like them very much. My typical #regions are fairly high-level, such as for properties and event handlers.

Brandon on July 7, 2008 08:18 AM

I think it's overuse that drives people mad not specific use. I often write stuff that uses crystal reports so can have 10 to 15 buttons on screen usually in a tab page each to run a separate report, they all have pretty standard code behind (not the same I couldn't wrap it into a call to a function or anything) and I hardly ever need to see it so I prefer to put it in a crystal reports button handler region. That means my core code is left visible the bit I know is correct is left alone. I don't think many people would object to that.

Over/Misuse is constructors, methods, helper methods, properties, fields... I often think people who do the regions this way are maybe missing the objective of the region it's not to separate your properties from your methods most of the time you need them both on screen.

pete on July 7, 2008 08:23 AM

Scanning code took too long for me so now i use the class selector and member selector drop downs, and then use regions to keep the code clean (of course, i don't make the regions myself, i have use regionerate to group and sort everything).

But that's just my preference

Darren Kopp on July 7, 2008 08:25 AM

You're spot on! Regions seem to flap about and get in the way of getting on with it. And dangerously folks seem happy to dunk stuff into a region, when they're too lazy to refactor code into a new class.

And Ctrl-I ... so few of my colleagues seem to use it. It makes me cringe when I see people Ctrl-F'ing slowly about because they don't bother to learn their tools. And, why do so many programmers seem to refuse to learn to touch type? It only took me a couple of weeks to get into, but makes working with a computer soooo much more fluid!

Scott on July 7, 2008 08:31 AM

You have good points there. I personally don't want to see loads of verbose code that is the result of adding some fancy new technology to the project. But that verbosity is possible to be hidden by encapsulating, not with regions.

For example you all remember The Evolution of Programmer example of coding levels: Basic programmer, advanced programmer, expert programmer etc., where the basic programmer does only 10 Print "Hello World" 20 Run, but master programmer has already pages of advanced C-code.
http://www.thehumorarchives.com/joke/The_Evolution_of_a_Programmer

Silvercode on July 7, 2008 08:31 AM

This is obviously a preference that can be overused. Just like pretty much everything else, it has its place if used correctly.

I feel more strongly about overuse of comments and even worse, inline suppression of Code Analysis...talk about making your code not readable.

BZ on July 7, 2008 08:32 AM

Hmm. I was going to argue that with proper use, #region is not so bad, but then I remembered a recent gem from a college. Here's a rough outline:

if (some condition)
{

J. Irvine on July 7, 2008 08:45 AM

Sorry for the double post... keyboard error.

Hmm. I was going to argue that with proper use, #region is not so bad, but then I remembered a recent gem from a college. Here's a rough outline:

if (some condition)
{
#region Foo
...
}

if (some other unrelated condition in another block)
{
...
#endregion
}

J. Irvine on July 7, 2008 08:47 AM

Jeff,

if code is not readable, or if it is readable only if "folded", it is very likely that it is not the best "cut" of code.

Folding is for laundry. Optimization/Refactoring is for code.

BugFree on July 7, 2008 08:47 AM

I agree with Jeff enitrely about this, though I am not neccessarily qualified to comment.

I'm a PHP5 developer and I use EditPlus as my editor. It has a kind of 'hacked in' code folding which turns out to be exactly what I want - it gives you the little expand/collapse button for any section of code that is at the same level of indentation. Its not very elegant but it has a suprisingly high percentage of the value of "real" code folding without any of the effort. (Your code is all properly indented, right?)

I don't need to hide away class attributes, getters and setters and such because PHP doesn't have any of that crap unless you want it - and then you want to see it. What I *do* sometimes want to do is things like collapse the 'true' section of a large

if( ... )
{
...
}
else
{
...
}

block so I can see the condition right next to what happens if it is false. Or hiding away divs in a HTML/template file so that I can see the surrounding structure (hunting for that unclosed tag!).

It is zero effort on my part and is there for the very rare occassions that I want to use it. If you want to give your region a description, just use a comment :p

Mat Scales on July 7, 2008 08:51 AM

I prefer KDevelop/Kate's way of handling it: Every block-level statement (ie, anything within braces) is collapsible. So are similar block-level statements in languages like Python, which don't use curly braces.

In KDE4, Kate is also capable of highlighting a block if you mouse-over its collapser...

And yes, it can handle #regions inside C# code too! I just tried.

shash on July 7, 2008 08:57 AM

clearly, all those years of web developing have saved you from seeing any problems, which actually do require a huge ugly block of code to solve... :P #region is handy if you have such a block of code, and with MSVS its neatly wrapped into the ide so you just select the area and choose to outline it.

generally i am in favour of splitting things out into seperate files, however once it gets down to the "one method" level, i think its pretty silly to split it into more procedures/functions just for the sake of keeping it in smaller chunks. sure you /can/ wrap it into lots of little procedures, but i'm not a fan, as it breaks the ability to read the whole code in sequence without swapping files, or moving around in a large file.

at the end of the day if you want to see what is in the region, you expand it... i really fail to see the big deal there as encapsulating things in procedures has precisely the same problems in terms of maintainability and readability which have been described in the article for regions, except for that nebulous point about it being like a glorified comment... if anything its slightly worse because you can't expand the procedure in place to see its precise effect, but need to use some (implicitly error prone) thinking to substitute variables and remember things between two different files etc...

can anyone remember the early visual basics btw? they had this awesome feature where by you looked at one procedure at a time in the editor, even though they all came from the same file. its a shame they dropped it in vb 5 or 6 (can't remember which). i think that old feature is a much, MUCH, better solution than what we currently have in the more recent visual studio products.

Jheriko on July 7, 2008 08:58 AM

Jeff, Jeff, Jeff...

Have you truly LOST it and gone all "religious" on us? It's a formatting technique, my friend. Properly used, folding regions allow us to reduce the problem set by managing the complexity of a code file. That IS what our friend Steve McConnel preaches, isn't it? That our goal is to manage complexity?

With strategic use of folding regions, we can keep the screen clear of code irrelevant to our immediate purpose. Your argument that "irrelevant" code belongs in a different file depends entirely on context: the small part of the code I am working on may very much belong in the file, but I don't want my eyes continually distracted by code for methods and such that have nothing to do with the particular problem I'm working.

How do YOU know what I want to focus on? What SPECIFIC thing I'm trying to understand or debug? How do YOU know that the best way to organize my code for focusing on one problem may be completely counterintuitive to the solving of a different one? Being able to collectively collapse/expand regions of the code AS NEEDED is a great way to keep your mental focus flexible.

I'm a fan of yours, and I mostly agree with your musings/insights, etc., but I'm afraid if we were on the same programming team, I'd be standing my ground on this one.

Wing Flanagan on July 7, 2008 08:58 AM

shash: visual studio provides the same functionality out of the box, minus the selection thing you mentioned, which does sound useful. :)

Jheriko on July 7, 2008 08:59 AM

I think Regions were introduced to .NET because the Microsoft programmers had the problem of autogenerated code. They needed a way to tell us hands off to the "Web Form Designer Generated Code" section. In 2005 and beyond, they simply introduced another feature, Partial Classes, that got rid of the the horrible hand off region section. Now, the MS developers can put all of their code in one file, and leave a clean file for us to work in.
I will second the comment that someone above made about VB6. There was a button in VB6 that you could press to view only the currently selected function. I used this all the time in order to make my scroll bar increase from hairline size to something I could actually click on.
In my opinion, regions and collapsible code have the same function in that they allow you to shrink the size of your scrollbar at will.

Jay on July 7, 2008 08:59 AM

Generally, I think #regions are helpful, when used in moderation. I like each of my files structured similarly (declarations first, properties second, events third, and public/private methods last). Because of this, I usually wrap the declarations, properties, or both into #regions so that when I open a file, I don't see a bunch of rarely touched code. When you say that everyone should be able to see all the (crappy) code, I agree; however, I don't think we should have to look at a few pages of declarations/properties that are probably fine. If I know there is a bug on Page_Load, I don't want to have to scroll down a ways to see the beginning of it. Also, this doesn't take much time to type. When I create a new file, I easily the #regions using a code snippet on my machine. You said that "the editor should automatically offer to fold up these common structural blocks for you!" Unfortunately, this doesn't happen now, so I will have to do it in the meantime. If the next version of Visual Studio starts to do this, then maybe I will drop #regions altogether.

Mike on July 7, 2008 09:04 AM

Reducing visual noise is a wonderful thing. If I don't currently need it, I don't want to see it. Within code files, MS chooses the plus/minus expand/collapse approach as a big stick to get this accomplished. Regions allow us to introduce collapsibility into our code that isn't provided out-of-the-box.

This is analogous to menus, treeviews, toolbars, etc in UI design. You can use these organizational tools to make things easier to use and find, or you can create a mess.

Whether you implement regions in a useful way is up to you.

Chris on July 7, 2008 09:05 AM

"You're not just advocating abandoning #region you got it in for comments to!? You gone CRAZY man!"

Ditching regions and just having the option to have it open folded down to signatures would work for me, but that said I'd also like some options to allow me to sort methods (in a similar way to the current sort usings). I think that maybe because I also like to use class and method selector drop downs, as well as right click -> go to definition, so alphabetical works for me.

As for comments I think I'd like to see the class and method comments moved to a seperate file as they've rarely been useful on code I'm working on. I've only really found them useful when you got the dll for some third party library and no source to reference, even then I've often had to resort to reflector to find out what's going on as they're often written by people who know how the library works without enough consideration for those who don't.

MarkM on July 7, 2008 09:08 AM

Those who point out auto region expanding miss the core problem with regions -- if your coworkers are praying at the idol called regions, that externality infects the codebase. It strongly motivates how the code is structured, conforming with a generally poorly thought out use for regions.

Seriously, when people talk about accessibility or finding methods / properties / fields, and how regions help the same, it screams from the mountaintop that they are woefully unaware of the rudimentary features of the IDE (guess what -- it already tracks all of these, each navigable in the desired manner when the need arises).

Dennis Forbes on July 7, 2008 09:11 AM

Jeff, I think you take this a bit too far. Firstly, you get a little sloppy with your argument:

"The editor should automatically offer to fold up these common structural blocks for you!"

This came *right after* all the argumentation that folding is so bad because it hides code that shouldn't be hidden (which I happen to think was good argumentation).

One other thing - folding can be useful without all the problems you have with it. Take Emacs folding for example - if you need to refactor a function, but don't know all the commands or keyboard combos that have regional effect instead of buffer effect, you can use folding to put a region into a buffer of it's own, and then use buffer-wide commands there, and then jump back into the original buffer with the edits you made intact. Folding can be useful for things other than just hiding code.

aggieben on July 7, 2008 09:15 AM

Just a quick comment to say *Thank You*, Jeff.
I just had a bad, bad, bad moment last week when I opened the Nth file that was all #region-ed. My scream of 'AAARGH !' was greeted by blank stares (and a few bad looks) in the room. sigh

F.O.R. on July 7, 2008 09:16 AM

I use 'vi' folding with 'set foldmethod=marker' all the time.
I only fold up functions, however, and my 1st line of the fold has enough info to infer what the function does.

This allows me to see what functions are available at a glance,
while working on the main body of the code (or while looking at a new function in progress).

vi (actually vim) will drop me back off where I was upon opening the file, so if I'm already in a fold, it's open when I start.

When working with fairly standalone application and a small developer base, the codebase resides nicely in a single file. This helps hide any deficiencies in the infrastructure, such as poor installation/distribution support and versioning :-)

So I find the ability to fold code (and textfiles of notes) very valuable... but with any 'feature' of the editor, it can be abused.

eric on July 7, 2008 09:17 AM

Jeff,

Not being very constructive now, are we? Sure regions can be bad when used in the wrong way, as stated in many of comments. I can feel your pain since the code I'm working with atm is full of all the wrong kind of regions. But that is no reason to outright outlaw the usage of regions. Used in the right way they can be quite a help.

Better to educate the community of when and how to use regions and in the end we will all be better off.

Robert Höglund on July 7, 2008 09:20 AM

It isn't hard to toggle outlining, are we really getting to the point where we're complaining about the effort involved in hitting a shortcut key?

I use regions quite often, but I also treat them a little differently. I keep them all expanded, but I color the directives a bright pink so they stand out. I use these bright pink directives to group static members from instance members, properties from methods from events, etc. I can quickly see them as I scroll through the file. You can also quickly jump to regions if you're consistent in your naming.

Brett on July 7, 2008 09:28 AM

I have been usisng a folding editor for 10 years or more. yes it can hide lots of bad code, but conversly, when I open a file I can see instantly in front of me the structure of the module. Without folding I temd to see half a page of includes, and quite often some helper functions - this does nothing for me.
Our deperatment is fairly 50/50 split on folding, but we all get along!

Ian Cummings on July 7, 2008 09:30 AM

In addition to my previous comment, regions are great in WPF when you don't want to see all the junk associated with dependency properties, routed events, etc.

Brett on July 7, 2008 09:32 AM

Count me in as fan of regions. As others have said, they are useful for hiding the likes of numerous attribute declarations, etc.

However, I do agree with most of your objections, they are very prone to abuse. Many times the desire to use a region can be taken as an opportunity to consider refactoring. That's the clue I use personally in any case.

I also feel your pain, there is a member of my team who shall remain nameless that insists on profuse (imo) use of them. It is painful to read files he's written.

Seth on July 7, 2008 09:39 AM

Right click, Outlining, Stop Outlining.

Job done. But you knew that already.

Tom on July 7, 2008 09:49 AM

Meh. I think the most important takeaway here is that #regioning is a code smell. For me, I don't see much regioning since I usually browse by "Go To Definition", which necessarily expands the region.

John on July 7, 2008 09:54 AM

Sounds like most of the proponents of code-folding believe that it reveals the "outline" by hiding the details. I submit that, when we're looking at code, "the devil is in the details"

Regarding partial-classes, my .02 is that they should only be used to separate auto-generated code from programmer-generated code.

Wile_E_Coyote on July 7, 2008 09:59 AM

@Wile_E_Coyote:

As I said above, if you have to delve into the implementation of a class before you can use its public interface then that is a definite code smell!

Graham Stewart on July 7, 2008 10:11 AM

I do not know how Visual Studio works, but emacs incremental search is so not-painful to use that I can't really express it. I see this folding "feature" that my friends from college use and I have been only disgusted with how much time they lose using the mouse to code while using it (and other features from those fancy IDEs).
I have been using XEmacs to program in C for some months now and I can say that I will probably still use it for the rest of my life.

Hoffmann on July 7, 2008 10:16 AM

I used to commonly write a class and then reorganize my methods into groups that were logically related. Once I had all these nicely formatted regions I would then realize that each one represented a class that my original class should be refactored into.
Of course, I didn't refactor; I just stopped using regions.

Brad on July 7, 2008 10:16 AM

@Tom: The best part about that is that no matter your preference on this issue, both sides can peacefully co-exist!

Adam on July 7, 2008 10:21 AM

I've got two outline regexps for C++ in Emacs. One uses only method names and doxygen headers, the other adds on method-internal comments.

I defined these at first to get the IDE feature into Emacs, but I've stopped using them lately. Between tags-apropos and C-s/C-r I haven't needed folding.

Remember what Steve Yegge said about arranging stacks of screens of Tetris games? The #region problem is a symptom of your larger issue: boilerplate demanding superhuman code organization. You need an IDE so you can use your IDE. I think he's got you on this one.

Dan Lewis on July 7, 2008 10:34 AM

The main issue i have with regions is it forces all viewers into the same visualization of the code. Weather or not it is a good organization or not it forces that View of the code on the reader. When a class with regions are poorly organized it harms all viewers.

And poorly organized is relative to the ideal conceptualization you need, ie: the mental picture.

The most common and in my mind most annoying #regions are grouped by:

ctor
fields
properties
methods

Why? This is arbitrary organization based on the parts and not a conceptual model. It would be like organizing a book based on verbs, nouns etc instead of the normal conceptual model, units of time (ie chapters).

Good organization would be regions based on Interface implementations, Class overrides etc.

For instance:

# IPerson

# Control visual element hook-up

This organizes based on logical separation of concepts.

However this is still not perfect. Because any newcomer to the code will be forced to view the code with the organization I chose in my regions. If that organization doesn't work for what they are doing(the conceptual model they need), they are forced to work against that model. They will end up expanding the regions, trying to block them out mentally, while attempting to make the code coherent in their mind.

brian on July 7, 2008 10:42 AM

@Paul

"There's a lot of things Visual Studio could do better if Microsoft bothered to copy the competition."

Correction:

"There's a lot of things the competition could do better if they bothered to copy Visual Studio."


C'mon, the last time I tried Eclipse (no that long ago), it didn't even have File | Save As. Not in every case, but generally speaking, Visual Studio let's me get my work done without a lot of BS. Most of "the competition" may have some fancy new features that are very well done, but then basic stuff that Turbo C++ had 20 years ago isn't even there.

Coder on July 7, 2008 10:42 AM

I definitely think it is very bad practice to utilize editor/IDE tricks to avoid having to make things readable. Just hiding the ugly bits of the code, instead of actually spending the time thinking about it and finding a cleaner way, is just another lazy way of injecting spaghetti into your system (gotos were useful too). It is the type of problem that only gets worse with time. It is far easier to make a mess, then it is to write decent code.

Paul.
http://theprogrammersparadox.blogspot.com/2008/06/readability.html

Paul W. Homer on July 7, 2008 10:44 AM

This is a lot like the 'var' discussion. Yes, in the wrong hands it can be misused. If you're a bad programmer, you'll always be a bad programmer, no matter what language, Studio, or how many or how few language features.

Don't gimp my language/tool because someone else might misuse it!

This is why everything comes with a damn warning label: "Caution: if you're a moron you might cut yourself with this knife."

Dennis on July 7, 2008 10:47 AM

EMACS

I want my editor back!

1970 on July 7, 2008 10:49 AM

'Don't gimp my language/tool because someone else might misuse it!

This is why everything comes with a damn warning label: "Caution: if you're a moron you might cut yourself with this knife."'


Dull knives cut fingers... not sharp ones.

brian on July 7, 2008 10:53 AM

@Paul: > "I definitely think it is very bad practice to utilize editor/IDE tricks to avoid having to make things readable"

It's worth pointing out that #region is NOT an editor/IDE trick.
It is a recognised part of the C# language, according to the ECMA standard:
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf (see section 9.5.6)

Graham Stewart on July 7, 2008 10:57 AM

Emacs is getting a lot of attention in this post. I think it's because it was the first IDE (or one of the first), so basically everybody wants to compare a cool feature with the one that is presented in emacs. Emacs is so, so old that is hard to consider anything that does it differently from Emacs to be better. For most things that is true, for others it's just a different convention derived from the enviroment. In the case of incremental search I belive it's hard to be better than emacs, ctrl+s to incremental search forward from the cursor, ctrl+s again to search for the next word, the same with ctrl+r for backward search.

Hoffmann on July 7, 2008 11:11 AM

I've been reading this blog for a few years now and I normally agree with about 90% of what Jeff writes about, but I highly disagree on this matter. While writing clear, concise, logically-organized code is certainly the goal, we all know it's not always possible. I do the best I can, but there is often a lot of extra setup code and such that I don't need to see while I'm working on other things.

And having wrestled with ADHD/Primarily Inattentive Type thoughout my life, the ability to easily hide sections of code that I don't need to be concerned with at the moment is probably my single favourite feature in VS.NET (as compared on VS 6.0). It's a huge productivity booster for me to be able to selectively hide pieces of code that distract me and contribute to mental clutter. I would guess that most programmers probably can't relate as I don't think that the ADHD "brain style" is especially suited to the task of programming.

Keldryn on July 7, 2008 11:18 AM

@Adam, I don't know about peacefully. It's been something of a jihad in our office to get people to quit hiding their code. Our team makes everything public too which killed our credibility with the "smarter" guys. [lol] We just value Rhino Mocks and testing more!

Jason on July 7, 2008 11:26 AM

It large files this is incredibly helpful... less you scroll forever and ever to find what you need. The extra mouse click to open them is well worth the time it would take to scroll through a whole bunch of stuff you don't need.

Kris on July 7, 2008 11:28 AM

I initially didn't like regions, but then I started working with larger code files and realized how useful they can be. My biggest disagreement with Jeff's four points is number 3. Sometimes you may have a perfectly clean code file that simply *has* to be long, for various reasons, and regions make it easier to get around and find the parts you're looking for. So put me down in favor of #region.

Chris Tybur on July 7, 2008 11:36 AM

I love regions. If you did a survey, I bet 90% of
Visual Studio developers will say they use regions
and love them.

Jim White on July 7, 2008 11:46 AM

I think that it might be good to point out that the editor in question already does code folding on the function level (and the xmldoc comments have built in folding already too). regions are a way to group collections of functions into a higher level bucket that can be folded at one time.

That being said, I prefer smaller, lightweight code bases that do not require massive folds to make things manageable.

Ben Evans on July 7, 2008 11:49 AM

It often amazes me how narrow minded and "black and white" we coders are. Everything must fall into "good" or "bad" buckets.

Yes, if you write crappy code and then hide it #regions then your a loser, but it isn't the #regions that made your code worthless...It's your code. Taking it out of the regions (or putting it in) didnt change the code.

Instead of looking at it a "hiding", I prefer to think of it as "black boxing". That code is solid and stable and doesnt need to be thought about.

But this idea of "whining" because we had to set one more config option in order to not have to expand the code manually is a little absurd.

I would rather see that someone took the mental-time to organize the code in some fashion than to have to hunt all over to get from method to method.

Just my two-cents....

Baffled on July 7, 2008 11:52 AM

I used to think that regions were great until I opened up a file that someone else had written and all of the code was folded. It was a waste of my time to have to unfold it all so that I could read the code and get on to my task. Now I don't use regions. I also disagree about folding comments. If the comments are useful than they should be visible. If there is a reason to hide them in a region, then maybe the comment shouldn't be in the file.

asm01asm on July 7, 2008 12:03 PM

Why are people complaining about code-hiding? We do it everytime we create a class file. If you don't loke hidden code, then by all means code in a text editor. Textpad is where I do most of my coding in. Sure it doesn't do any autocompleation or other nifty gadgets, but your code is EXACTLY the way you want it.
<sarcasm>Make everything Global while you are at it. After all Global vars and expressions are faster and cleaner.</sarcasm>

Mark on July 7, 2008 12:09 PM

Right on, Jeff! In practice, regions are a band-aid on bad code. They seemed nice when they were first introduced. Now, I wish they'd never been introduced. They give the illusion of nice, neat code. If you need to organize the code, use the language elements to do it. Also, I can't stand having to open those damned things up. I don't need all the properties in one place, all the private methods, in another.

JohnOpincar on July 7, 2008 12:22 PM

I have to agree, but it's an opinion I don't hold as strongly. They annoy me, but I don't actually hate them.

Jeff Davis on July 7, 2008 12:29 PM

> In 2005 and beyond, they simply introduced another feature, Partial Classes, that got rid of the the horrible hand off region section.

This is a great point -- until Partial Classes existed, #region was necessary to hide the required generated code.

> As for comments I think I'd like to see the class and method comments moved to a seperate file, as they've rarely been useful on code I'm working on. I've only really found them useful when you got the dll for some third party library and no source to reference.

The presence of massive XMLDoc comments bothers me as well. It's necessary, but it gets in the way so often.

The fact that we even *have* a #region directive is part of the problem. With a good editor it shouldn't be necessary, and all folding would be optional. I wish the Visual Studio editor was smart enough to fold XML Comments down automatically -- or even fold down methods automatically. It's not, even in 2008. Example here:

http://www.codinghorror.com/blog/archives/000332.html

Jeff Atwood on July 7, 2008 12:29 PM

I have read about this kind of VS code folding before and I did not like the sound of it at all. I have never liked any kind of code folding at all until i started using mylyn (except maybe some minor imports and comments folding).
Eclipse + mylyn that does class/project tree folding and source code folding that is associated with a task. The task can be an issue in an issue tracker and you can save the task's folding into the issue tracker. It is really good when working with both big and smaller sets of files.. I guess that most of you know this but anyways...
Here is some information on mylyn folding: http://www.ibm.com/developerworks/java/library/j-mylyn2/

Thomas on July 7, 2008 12:30 PM

A lot of people here seem to think that regions are the *only* way to hide code. But they're not the only way, nor even the best way. Here's a better way.

In VS, go to Tools > Options > Environment > Import and Export Settings. Copy the path and filename in the "Automatically save my settings to this file" box. Then open that file for edit. (Not sure if you can do this in VS and still have it work right, but otherwise use some other XML editor.) If in VS, hit Control-K, Control-D to format the whole file so it's readable.

Find the KeyboardShortcuts section. Then find the UserShortcuts section within that. If you've customized your keyboard at all, you should see various lines starting with Shortcut or RemoveShortcut. (If you can't find these sections, go into Visual Studio, customize a keyboard setting, then open the .vssettings file back up and look again.)

In among the Shortcut/RemoveShortcut lines, paste these:

<Shortcut Command="Edit.ToggleAllOutlining" Scope="Global">Alt+Right Arrow</Shortcut>
<Shortcut Command="Edit.ToggleOutliningExpansion" Scope="Global">Alt+Down Arrow</Shortcut>
<Shortcut Command="Edit.CollapsetoDefinitions" Scope="Global">Alt+Left Arrow</Shortcut>
<RemoveShortcut Command="View.Forward" Scope="Global">Alt+Right Arrow</RemoveShortcut>
<RemoveShortcut Command="Format.SpaceAcross" Scope="VC Dialog Editor">Alt+Right Arrow</RemoveShortcut>
<RemoveShortcut Command="Edit.CompleteWord" Scope="Text Editor">Alt+Right Arrow</RemoveShortcut>
<RemoveShortcut Command="View.NavigateForward" Scope="WebBrowser">Alt+Right Arrow</RemoveShortcut>
<RemoveShortcut Command="Format.SpaceAcross" Scope="VC Dialog Editor">Alt+Left Arrow</RemoveShortcut>
<RemoveShortcut Command="View.Backward" Scope="Global">Alt+Left Arrow</RemoveShortcut>
<RemoveShortcut Command="View.NavigateBackward" Scope="WebBrowser">Alt+Left Arrow</RemoveShortcut>
<RemoveShortcut Command="Format.SpaceDown" Scope="VC Dialog Editor">Alt+Down Arrow</RemoveShortcut>


What does this do? It remaps some Alt+arrow keys. Alt-Left now does Collapse to Definitions; Alt-Down toggles the item you're on; Alt-Right toggles the whole file between completely expanded and completely collapsed.

So when you open up a code file and the code is sprawled everywhere, just hit Alt-Left and it collapses neat and tidy, but you can still see the members. On the member you want to work on, hit Alt-Down to open it. (Or just double-click on the [...], of course.) If your file contains several classes, use Alt-Right (you may have to hit it twice) to collapse everything, even the class definitions, so you can open just the class you want.

All the code hiding you could ever dream of, and you don't have to use regions for any of it.

Kyralessa on July 7, 2008 12:30 PM

What's the big deal against regions? It's just a cheap IDE trick - didn't Code Complete wish this existed a while ago? Any feature/trick can abused if misused by an bad coder.

I peronally love them - I hide away my member/property declarations for when I'm not dealing with that stuff and working on business logic. Sure I can scroll to the bottom, but why bother every single time? I use it as a part of a naming/layout standard - which I actually picked up from a dev team on a gig.

As per my twitter post - you're illogical to me on this one - I think implicitly typed local variables can get you in about a billion times more trouble in the wrong hands than regions.

BPAndrew on July 7, 2008 12:31 PM

Is it okay to trash developers that are no longer on the team? :)

thedp on July 7, 2008 12:32 PM

I agree with you 1000%, Jeff. I think the comment "regions are a code smell" is spot on. Using regions to "organize code" or "manage complexity" is using them as a crutch to enable inordinately long code blocks and poorly factored classes. A class or method that is complex enough to need regions is almost certainly doing too much.

I too hate the fact that when you open the code in the editor you don't see the code. If I didn't want to see the source, I wouldn't open it, dammit. I always disable automatic auto-outlining in Visual Studio for that reason (and region generate for interface implementation as well).

I also find that regions are rarely applied consistently. Some people fold by property/method/constructor. Others by public/private/protected. Neither really add any value, they just make it harder to navigate the code.


Kevin Dente on July 7, 2008 12:40 PM

I have to completely disagree. Boilerplate crap is a fact of life in the Windows programming world, and the #region directive brings some kind of sanity to that.

If you really want to navigate your code base you're not doing it by scrolling through a single file's edit window anyway; you're using Ctrl-F12 to skip through definitions or using the class browser.

Andrew on July 7, 2008 12:40 PM

I'm not sure if that's been mentioned before and I'm not ready to read 150+ comments (sorry!) but I think I've got a point worth mentioning.

I believe that, unfortunately, and despite good intentions, Regions should be considered evil. Why? Because they lie. Region titles make strong claims, e.g. “Private members” claims that this region only contains private class members. But of course, the compiler won't check this assertion, it won't check whether the region really doesn't contain public methods.

I've come across situations where I've searched myself silly because the region captions were lying to me (and yes, I wrote these captions so I'm guilty). But the fact remains that this has cost me much time and I have learned to give any constructs that give redundant, unchecked information a very wide berth. Regions, in my opinion, are very good at hiding vital information while making false claims.

Konrad on July 7, 2008 12:47 PM

First you whine about XML. Then you advocate using "var" for everything, even when the type isn't obvious. Now you whine about code folding.

Opinions are like assholes, but to me it looks a lot like you're still steeped in your old VB habits and these posts are all pining for simpler times.

Production code has cruft and boilerplate. It just does. Real applications are never nice and clean and short and perfect and academic. Regions are a band-aid, most certainly, but as an alternative to an open wound I'll take 'em gladly. And if your solution is "just don't cut yourself", then I'm sorry but that's simply not acceptable.

Aaron G on July 7, 2008 12:48 PM

Regions are an organizational tool. They can be very helpful, and if you haven't found them to be so, then that's fine. I've yet to run into a situation where regions were involved and my life was on the line...maybe everyone else here works in a more intense environment than I do.

Outlining can be turned off within Visual Studio, and as it has been pointed out, everything can be expanded in a couple of quick clicks. So it seems like the worst your co-workers have done is added a few goofy lines (similar to some odd form of commenting) to the otherwise pristine code. Since any good code file is apparently contained in approximately one to two pages (as I've learned from the comments), then I don't see that this is really worth mentioning.

It seems to me that the two arguments that keep coming up against using regions, have boiled down to something like this 1) I've seen abuses of regions, therefore regions suck, or 2) *I* don't like regions; therefore regions have no value; therefore if *you* need to use regions, then you're obviously not up to snuff on your mad koding skillz!1. There's some dogmatic assertions here today.

And besides, if you don't see the usefulness of regions, then, obviously, you're doing it wrong ;)


Steven on July 7, 2008 12:55 PM

The problem with Text Folding.

I hate chapter titles in books. When I open a book what do I see? The Table of Contents! Immediately I have a problem! I can't see anything! Every time I open a book I have to manually turn past the damn Table of Contents. WTF? Each section of the book has a stupid "Chapter Title". I want to see the damn text! If I want to know what the text is about I'll read it! And some of these "chapters" are only one page long!!

I daresay being able to see the damn text is more important than having it meticulously segmented into pointless little named buckets, but apparently a lot of authors can't get enough of stuffing their prose into pointless little named buckets. It's as if they've forgotten what scanning -- and an index -- is for.

1. Chapter titles are glorified comments.

2. Chapter titles are used to sweep text under the rug. I once saw a book with only three "chapters" and it was 400 damn pages long!

3. Chapter titles are used to mask excessive length. See #2.

4. Chapter titles can hide deficiencies in your writing tools. Why does someone have to create these? They should be generated by the author's word processor, or typewriter, or steno pad!! Aren't all books the same? Protagonist, antagonist, love triangle, misunderstanding?

I urge authors to write stories that don't need chapters to be readable, clear, and concise. I'm sure there are sane uses