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

July 6, 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.

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 4: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 4: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 4: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 4: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 4: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 5: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 5: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 5: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 5: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 5:10 AM

The Eclipse IDE automatically manages code folding.

Niyaz PK on July 7, 2008 5: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 5: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 5: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 5: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 5:13 AM

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

snomag on July 7, 2008 5: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 5: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 5: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 5: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 5: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 5: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 5: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 5:29 AM

Oh and:

- Nested types

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

Jax on July 7, 2008 5: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 5:32 AM

dude, whats with the comment about terrorists?

Sameer Alibhai on July 7, 2008 5: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 5:39 AM

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

Loz on July 7, 2008 5: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 5: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 5: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 5: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 5: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 5: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 5: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 5:50 AM

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

I was wondering the same thing.

Arron on July 7, 2008 5: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 5: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 5: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 5: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 5:58 AM

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

Donny on July 7, 2008 5: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 5: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 6: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 7: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 7: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 7: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 7: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 7:17 AM

@Jeff

Or in a different class.

Totally agree, regions cause friction.

Resharper can help with that btw.

Matt on July 7, 2008 7: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 7:19 AM

Jeff,

100% agree. #regions blow.

Might as well have called it

#rugwithdustunderneath
#loadedgun
#tomaximizeyourcodingtimeandeffortlookherelast

John Pirie on July 7, 2008 7: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 7: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 7: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 7: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 7: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 7: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 7:31 AM

Automatic folding? Use VIM. :)

Bruno Nery on July 7, 2008 7: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 7: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 7: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 7: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 7: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 7: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 7: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 9: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 9: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 9: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 9: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 9: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 9: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 9: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 Hglund on July 7, 2008 9: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 9: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 9: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 9: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 9:39 AM

Right click, Outlining, Stop Outlining.

Job done. But you knew that already.

Tom on July 7, 2008 9: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 9: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 9: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 for chapter titles out there somewhere, but I rarely see them.

Non sequitur on July 7, 2008 1:00 PM

I think if codebases have to be really big, this is a good argument to use .NET partial classes. Separate the chunks of those big files into different files.

They may logically belong to the same class, but at least they are in different files.

Jon Limjap on July 7, 2008 1:05 PM

Finally someone who hates this useless #region crap. I have the same opinion - it drives me crazy when I'm looking at someone's code and can't see a thing. Linus Torvalds once wrote: "if you need more than 3 levels of indentation, you're screwed anyway". If you need to use #refion - see above :-)

dereck on July 7, 2008 1:06 PM

And I don't get what it is over users being "afraid" of having a lot of files. COBOL programming, anyone? Everything in there is just under ONE BIG FILE!

Jon Limjap on July 7, 2008 1:07 PM

@Non sequitur

Haha, Perfect

Brett on July 7, 2008 1:15 PM

Like any new tool or technique, there is bound to be overuse and abuse until a consensus is attained about what constitutes a “best practice”. This discussion is part of the process of that consensus.

Personally, I admit to “hiding” my exception handling within regions. This allows the flow of the program to read unimpeded by exceptional occurrences.

John Keating on July 7, 2008 1:19 PM

I don't have quite the problem with code folding you do -- I think that like most things in 'programming' it can be used sparingly and make things easier for someone else to follow/read, or can be way overused and make things more of a PITA (like the way I feel about you and your 'var'ification... ;-).

In the end I find myself using less #regions and more bricks/patterns of whitespace (lines) between logical chunks of code.

N on July 7, 2008 1:25 PM

When I first heard of XMLDoc I thought it could be kind of cool and helpful, but the actual usage of it really pisses me off. It creates unnecessary junk - which to me says "I am a really bad programmer" - good programmers don't create unnecessary junk.

I saw this today:
''' -----------------------------------------------------------------------------
''' Project : DotNetNuke
''' Class : CDefault
'''
''' -----------------------------------------------------------------------------
''' <summary>
'''
''' </summary>
''' <remarks>
''' </remarks>
''' <history>
''' [sun1] 1/19/2004 Created
''' </history>
''' -----------------------------------------------------------------------------


Err... yeah... thanks for letting me know that: you used a redundant naming convention; you have nothing to say about this class; and it is really, really, really old. I don't care dude... don't waste my time and screenspace with this...

Jasmine on July 7, 2008 1:32 PM

#region Comment

// Coding Standard: C# Philips Medical Systems - Software / SPI
// 4.2.5. Rec. 4@110: Use #region to group non-public members... 19

#endregion

Christo on July 7, 2008 1:40 PM

Whenever I come across someone whom is extremely opinionated about coding style and intent on telling everyone else how they should indent or how they should name their variables, it usually is to compensate for the fact that they can't read code to save their lives.

Being able to sit down and read someone else's code is a skill that takes time to develop. Unfortunately, people try to mask the fact they cannot with such annoying antics.

Wait until an engineer throws some FORTRAN 77 at you. Any non-modern Fortran code is guaranteed to look strange to a modern programmer. What is the coding prima donna going to do then? Tell them to redo it all in Java or F#?

Jay Bee Ess on July 7, 2008 1:48 PM

region comment is very useful.

oh "perfectly written" is a myth. Unless you write the whole thing your self, or you spend couple of years in the hiring process.

unfortunately, programmers, developers, team leads, who ever, write crap and at one point someone else have to foot the bill and maintain this crap. Region makes the process less painful.

Sami on July 7, 2008 1:54 PM

I have to echo Darren and Mark on this - Regionerate + ReSharper = useful regions. I tend to leave them expanded all the time and just use them for code organization, not folding.

http://www.rauchy.net/regionerate/
http://www.jetbrains.com/resharper/

Bill Sorensen on July 7, 2008 1:55 PM

@Non sequitur

I know the purpose of your post is to make light of the article. However you are close to showing why Regions suk.

In the book analogy one thing is clear, you did not reorganize chapters the way that some bad programmers rearrange classes within regions.

Your comment is facetious when merely discussing books and chapters.

However if you then reorganized your chapters by Nouns or some other arbitrary way. You're comment would no longer be humorous, instead it explains why regions suk.

Imagine reading Harry Potter in some arbitrary order of chapters, first all indoor scenes then all outdoor scenes...(public/private)

brian on July 7, 2008 1:55 PM

Are you seeking attention?

Hussain Saleem on July 7, 2008 2:07 PM

This is a *new* *language* feature? hahahahahahahaha

// {{{ Rant

Vim has had code folding with markers like forever :)

// }}}

/* vim: set foldmethod=marker: */

Nicolas on July 7, 2008 2:10 PM

I saw a badly named variable the other day - God variables suck.

Redge on July 7, 2008 2:23 PM

Folding functionality can be useful, to hide code that just isn't important most of the time. Eclipse, for example, automatically folds all the import statements at the top of the file, since that kind of thing just isn't relevant 99% of the time.

That said, this #region feature sounds like it's being overused somewhat, as a workaround for having too-complicated code. Eclipse supports manually collapsing at the class and method level, but it's not a feature I use very often - it's almost always sufficient to use the outline view to get the high-level overview of the file, which can be set to filter out non-public methods, or private fields, etc...

Simon on July 7, 2008 2:28 PM

Another very good thought from codinghorror!

Dave on July 7, 2008 2:44 PM

Folding also adds *another* thing that has to be maintained. We used it in a few areas in Paint.NET at the beginning, and over time it just fell apart. I find that the automatic - and + in the margin in Visual Studio gives me enough control and granularity for letting me hide code when I need to.

Rick Brewster on July 7, 2008 3:01 PM

For those that don't like regions (or automatic outlining in general), VS has a preference to turn it off.

Tools > Options > Text Editor > C# > Advanced > Outlining

Simply uncheck the "Enter outlining mode when files open" box, and this discussion is over.

I personally love regions, not for grouping like members (e.g. public properties, private methods), but for grouping like functionality in a class. Makes finding the part of the code you need to work on much easier.

Jarrod on July 7, 2008 3:33 PM

I believe Eclipse, Geany, and Zend Studio offer automatic folding. With options on how to work it as well.

Josh on July 7, 2008 3:40 PM

I wish there was automatic blog-comments folding, so I didn't need to scroll 50 screen to get to the form ;)

Regarding actual folding, I believe it is a semi-smell that too much is going on in the same file. When you need to start folding, maybe it's time to refactor and reorganize your actual code.

Eran Galperin on July 7, 2008 3:52 PM

>> Your project is now full of crappy code that you can't see

I want to have this framed and put on the wall at work :-)

Daniel

Daniel on July 7, 2008 4:16 PM

Like many have said previously, #regions are fine if you use them correctly, I can see how they could have a negative effect, especially if they're nested...ugh.

Ryan Thames on July 7, 2008 4:18 PM

I am an experienced VB.NET developer, and I have no beef with #Regions. Granted, I have never seen them used to group by modifier, but if that's what floats people's boats. I used regions because I want to leave behind a maintainable application for the next poor fool -er um, lucky guy that inherits the task of caring for my babies. I apply regions in the service of clean and logical coding. I group mainly by functionality in my larger apps. In my smaller apps, comments alone should suffice. Speaking of comments, there is a striking parallel. Comments, like regions, can be over done, under done, or not used at all. Ultimately, we will make do with whatever we inherit. I appreciate the thoughtfulness of a developer who thinks of others and tries to make his/her life easier. That's just respect and courtesy. Use regions, comments and whitespace to make you shtuff easy to follow. Because of course, the next person won't be as brilliant as you. 8-P

Gray Fox on July 7, 2008 4:28 PM

I disagree to a point.

Like all things technological, it can be used for good as well as evil.

I use regions as carefully as I use any other coding construct, to organise sections of my code that are relevant to one point in order not to have 'noise' in the code I am reading. The argument is much the same as you XML argument, why have visual clutter when you can reduce it?

I have to agree with you, however, that 'under the rug' use of regions is using them for evil.

John on July 7, 2008 4:43 PM

I'm working on a 7000 line file at the moment (a data access class written by someone else).

Regions are making my life MUCH easier. I can easily find the section I need without having to scroll scroll scroll.

Yes, it would be nice if the code was more concise, and split into some more classes... but it's not - so I'll stick with regions!

deadcat on July 7, 2008 4:51 PM

Yet another in my long list of issues with Visual Studios.

Justin Yost on July 7, 2008 5:00 PM

@JetBrain: All modern environments have code folding--it's useless.
I hadn't heard of the #region before, but I like the concept a little bit, it lets you give a meaningful comment to your region.

I always wondered what it would be like having an environment that primarily showed comments--where code was more like comments, and comments were what people actually looked at when they were looking through the code base.

Overall, without the structure imposed on us by actual code syntax, I think it would be an utter mess--but it's an interesting concept.

Also, considering the "pro" comments I'd say that Jeff was absolutely on with his thoughts on "rather than hide the garbage under the rug, get rid of the garbage".

Every justification I see here is either "Legacy, we know it's garbage", data or junk-code like getters & setters.

Extracting any of those from your code can only lead to goodness (and be very liberal with the definition of "data", virtually ANY Ascii strings, HTML, menu/GUI text, regex expressions... anything that isn't actually procedural code shouldn't be in your code.)

Add to that the obvious--eliminate and completely refactor (don't just cut in half) any method that is more than a screen long, and any objects that do more than one thing.

Now code folding is of absolutely no use.

Bill on July 7, 2008 5:10 PM

I didn't read all those comments&thinsp;&mdash;&thinsp;but I can tell you that Visual Studio (from 2005 at least) HAS code folding for namespaces/methods/classes etc. Those protesting it's lack thereof should try actually using the program.

In other news, regions ARE good for hiding large lists of accessors. I hate accessors (properties/getters & setters&thinsp;&mdash;&thinsp;whatever you want to call them). Other than I don't use them a hell of a lot. Or any type of cold folding for that matter.

Christopher Hawkins on July 7, 2008 5:39 PM

Years ago I red a good rant about proper coding style that was written by a maintenance programmer. One of his peeves was that we are still programming with pretty much basic text editors, when it would be possible to create something better. One of his examples was that it would be much easier to notice errors in complex equations, if you could see them as they are usually written for humans to read instead of a single line of variables and operators.

I think folding is an attempt to move to that direction. Programmers really should be able to control what is visible/hidden, but instead of hiding parts of a text file, that momentarily unimportant stuff shouldn't be there in the first place. For instance, instead of text files, IDE's could show code in a zooming based interface. We mostly (I think) visualize program structures as some kind of paths or groups of interacting objects. Then why the hell do we use tools that assume we write them as page by page novels.

I'm sick of scrolling and jumping from file to file. I'm not saying that programming should be done by clicking pretty buttons or that source code should be rich text. I'm just saying that programming tools could use some usability innovation.

Bloodboiler on July 7, 2008 5:40 PM

I disagree with this article. Regioning is just another way of organising your code and of limiting the amount of noise your brain has to deal with when looking at a file (noise being defined as anything you aren't immediately interested in).

When you open a large source file and see slews of XML comments and code everywhere, your brain expends unconscious energy deciding that it's all irrelevant. When you open up to some nicely collapsed regions, that energy is saved and you can quickly find the relevant section of code. Repeat this process 500 times in a day and the needless energy expenditure quickly piles up.

Of course, benefiting from regions depends on their sensible use. Having regions like "public methods", "static methods", "private methods" is about as useful as a barrel full of pig shit. Like any other tool it needs to be used well to be beneficial.

Regioning makes files easier to navigate and information easier to partition into bite-sized chunks that your brain can more easily process without getting tired from sorting through a sea of green, black and blue text.

I think you're off the deep end on this one.

Dave G. on July 7, 2008 5:52 PM

Sorry - Code Folding is awesome. I wrote a patch for it in Vim.

You have to remember that *the mental state of the programmer* is the most important thing in programming, and being able to see everything you need on screen at once, and being able to fold away the unimportant parts, is critical.

Maybe how VS does it is crap, I don't know. But in Vim, my patch would allow you to search for a term (say, foobar->wizwoz) and then fold away all the intervening lines, with a certain number of lines of context around them. This allowed amazingly fast code refactoring, and for complex refactoring operations it allowed you to see all of your other changes all in one glance, which made it both faster and less error-prone.

Was a grad school project, and something I was probably the most proud of. Can be downloaded here:
http://www-cse.ucsd.edu/~wkerney/vim_bill.tar.gz

Readme here:
http://www-cse.ucsd.edu/~wkerney/vim_bill.README

Bill on July 7, 2008 6:20 PM

I think regions are OK for hiding and grouping code, so long as they're not abused to make nonsense groups. If your regions have names like "private fields", "constructors" and "public properties", please don't do that. Such groupings are not logical, and actually preclude any kind of logical grouping. It increases maintenance effort since people now have to add related things in different areas of the file; either that or they don't bother, making even more of a mess.

Mr.'; Drop Database -- on July 7, 2008 6:27 PM

Wow, 200 comments already, you seem to have touched a nerve...

I guess that my thought is that at least the developer is attempting to make the code easier to read... it's hard enough getting developers to comment their code, let alone regions.

Definately a high class problem you have there.

Rob on July 7, 2008 7:02 PM

The worst thing about #region to me has nothing to do with whether or not code-folding is a Good Thing or a Bad Thing. It's that it breaks a mental convention that I'm used to seeing in curly-brace languages, which is that lines beginning with a hash invoke some sort of "compiler magic". (Think #include, #if, and others from the bad old days of preprocessors).

The first time I looked at C# code with #region in it, I didn't know what to make of it, it actually disrupted my original task while I went off on a 20 minute tangent of reading docs to assure myself that it didn't in fact invoke some sort of compiler magic. I use Vim, by the way, and it's configured not to fold anything unless I explicitly ask it to.

This is rediculous to me. As far as I can tell, #region is completely ignored by C# compilers, yet there is already a syntax for making the compiler ignore things: it's called a comment. I can't find anyone who can give a compelling argument why a different syntax is needed for *this particular* compiler-ignored directive.

We regularly write comments designed to be parsed by IDEs, documentation tools, and even static analysis tools (vis SPARK Ada's formal verification mini-language). Why is code folding special in the VS universe? Numerous full-featured editors such as Vim have no trouble folding code on commented directives (or on other tokens of the language for that matter), and the commented syntax makes it instantly obvious to people using editors without direct folding support that the directive is semantically inert with respect to how the code will compile and run.

This discrepancy put a bad taste in my mouth for #region automatically, regardless of it's other merits. On the infrequent occasions I put fold markers in my C# code, I usually end up writing "// {{{" Vim-style markers just so I don't have to be mentally jarred by seeing something that years of curly-brace languages have trained me to think of as a compiler directive, but which is actually isn't.

Kyle S on July 7, 2008 7:23 PM

Good comments Jeff. I've long since strayed off the MS path and its amazing how much a free product like Eclipse can still trump the golden child of IDEs (VS) after all this time. Granted, IBM has dumped buttloads of cash into Eclipse but still...no excuse for mucking up your LANGUAGE with something that a smart editor can handle. Rofl, cakes.

I think crap like this is whats pushing talented coders away from the lower level languages and making them fall in love with Ruby and Python. They just want to get stuff done and not worry about junk that slows them down.

Adam Conroy on July 7, 2008 8:25 PM

Rock Scroll. Use rock scroll. See your code from on high and from down low all at once. Avoid regions. Use rock scroll. Rock scroll ftw.

Damn it's good. http://www.hanselman.com/blog/IntroducingRockScroll.aspx

secretGeek on July 7, 2008 8:44 PM

>>I use Vim, by the way, and it's configured not to fold anything unless I explicitly ask it to.

Right, Vim does it correctly, I think, and has a tremendous amount of power available to it (though you have to slog through a bunch of documents to see all the features).

It folds on a number of things, none of which masquerade as preprocessor statements.

Have a tremendously long switch statement containing a line or two of code for every letter in the alphabet? Tap two keys and vim folds down all the code within the nested brackets, allowing you to just look at the case statements. Etc.

Bill on July 7, 2008 8:46 PM

I call it "cheating".

Duk on July 7, 2008 8:49 PM

>> 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.

Did you actually say that?

I hope you are not wasting your time filing your documents in relevant folders, only to have the cabinet look organized. Geez… the health insurance cover isn’t going to increase just coz you filed it! And also you should spread them all out on your floor, so that you can see ALL of them ALL the time.

Preeti Edul on July 7, 2008 9:04 PM

Like most things, I have no problem with regions when used in moderation. For example, in my current environment, we have classes that have a lot of constants (sometimes as many as 100) inside of a single class. It's nice to wrap these up in a region, as well as other code that's important for the process to function but not important to look at.

Test fixtures are another place that I occasionally use regions. There may be a few hundred lines of SetUp and TearDown, which aren't interesting once it's completed.

But I do agree that regions just for the sake of having them is usually unnecessary. I definitely don't like the regions used in the sample in this article - if you're going to use them over an entire codefile, I'd rather see them as logical groupings instead of just by the type of members.

Joe Enos on July 7, 2008 9:10 PM

Regions are like knives. Which can be used abusively, for poor reasons.

http://icelava.net/forums/thread/1441.aspx

Aaron Seet on July 7, 2008 10:34 PM

"When you open up to some nicely collapsed regions, that energy is saved and you can quickly find the relevant section of code."
Not necessarily. You might spend more energy trying to work out if the relevant section is "Handlers" or "Miscellaneous". Or worse, "protected functions" or "public functions".
The major problem here is that region is either semantically defined, which varies wildly by programmer, or syntactically defined, which normally means that they've taken the one bit the editor handles most easily (sorting/filtering functions by privacy level), and layered a fold over the top. This would be fine if protected and public functions were always clear from context. But as there's no reason every function in your code can't be public, as long as everyone agrees never to use them (private by mutual consent *guuuh*), this simply isn't reliable,

Tom on July 7, 2008 10:41 PM

If your boss looks at this folded code he is going to think, "I pay you all this money and you have not written any code"

:)

rippo on July 7, 2008 11:20 PM

Well, overusing regions is bad practice, I agree. But this is another way for structuring the code, like splitting the classes to files. The same way one might say, that all the code should be in one file, because then you won't need to browse a huge solution tree. Just one file and ... incremental search ...

Papi on July 7, 2008 11:22 PM

Does anyone who dismisses regions as an excuse to hide crap code or avoid refactoring actually work in the real world? I'd love to spend time refactoring some of the poorly designed projects i've had to work on but I can't because I have a steady stream of new jobs coming in which might actually help the company I work for turn over a profit. I can picture the conversation with my boss now.

"Sorry boss, can I delay starting on project x for a couple of days, i'd like to do some work on project y"

"Why, whats wrong with it?"

"Well, nothing really, but the some of the classes could do with refactoring..."

Anyone care to guess what the answer will be? I'm always re-assessing and where necessary trying to refactor my work but it's something I have to fit into time between projects or in those rare instances where I find myself at a loose end.

There are a couple of people where I work who are the sort of people who get wound up about coding preferences and the like and blog about this sort of crap, who are coincidentally the least productive programmers we have.

In any case, joining a project and refusing to adopt any conventions that the other developer(s) may have taken time to use is plain arrogant. I hate hungarian notation, 'm_' variable prefixes etc but i'll use them if it's consistent with the project i'm working on. Likewise, I expect other developers to show my projects the same courtesy.

Rick Mather on July 8, 2008 12:07 AM

I like regions in the auto-generated code from some of the visual studio templates. Hiding all that crud is nice.

I'd never put them in my own code, and I remove them from it whenever I implement interface (it always sticks in a #Region - annoying).

#Regions don't kill code, coders kill code (if they've got a #Region)

Andy Burns on July 8, 2008 1:10 AM

I also disagree. In team environments a consistent way of organising code makes things easier to navigate. It's not always about finding something, I would argue that more of the time it's about browsing through code that has been written by someone else - if you are familiar with the organisational structure of the code, its a great help.

Using regions is good practice.

Jimbo on July 8, 2008 1:39 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?

That's stupid. Tha'd be like "if you're constantly retouching your car's breaks, you should move the breaks to the back seat for easier access".

Regions are -like many tools- an excellent service the VS provides that could be overused, misused or well used.
Banning Regions just because you don't know how to properly use them is foolish Jeff. You contradict yourself so many times… you don't want "visual bloat" but you prefer to have a file opened in front of you with xxxxx lines of "this is not the code you are looking for".

Grouping things in a reasonable way is because our brains do not have the power of the IDE to just "jump back and forth" of the code. Regions help us to hide things and group stuff.

I group all the Delegates/Events, Public properties, etc. Because I know when I open the file, what I'm looking for. I just expand the part I want to see. and search from there. Less scrolling.

Also VS2005 CRAWLS when the file is converted from 2003 and was a "big form" where there's lots of Interface Designer code. So having Designer code collapsed really makes the file usable again.

Martin Marconcini on July 8, 2008 1:58 AM

I agree. In a team environment where you're working on code not written by you, you're usually more interested in how the code of the class interacts, not whether it's a "public instance method" or a "private static method".

An example as a maintainer: the first time I look at a class, I know I'm looking for something that sets "Foo = Bar". I don't know whether it's a "public instance method" or not, this information is just noise. I'm interested in WHAT THE CLASS IS DOING, not whether the programmer chose to pass a 'this' pointer to a method or not.

#region folding hinders maintenance for people not familiar with the code.

STeven on July 8, 2008 2:09 AM

One thing this post has surprised me with is how many people apparently seem to be using alternative editors (such as Vim or Emacs) to write C# code.

(Don't want to start a "One True Editor Holy War" here - I'm just surprised that Unixy editors are so popular on an essentially Windowsy language)

Graham Stewart on July 8, 2008 2:18 AM

I agree it's a "religious" choice, but I do find some good uses for a #region (I'm still working on VS2005):

- In a WinForm, a #region is handy to collapse all the declaration of UserControls (as well as the InitializeComponents)
- Again, in WinForms, wrapping the Event Handlers in a #region is a good idea, since they never contain the real code for that Event, which is usually written in a separate method (to be used from different events, with different EventArgs)

I use #region a lot, it helps me organize the code overrides/implementations for the different base/interfaces of my classes.
But, to be honest, I've found a big negative point for #region: when many programmers write on the same classes, they do not share their "mind patterns", and sometimes methods switch from a region to another with no apparent reason, new methods appear in a region they shouldn't be in, etc.
My solution: I check all the code and decide where to place the regions, then I make sure I'm the last one to check-in all the files :-P

Filini on July 8, 2008 2:40 AM

heh, once when I was contracting I saw the "best" ever use of regions.
A 10,000 line method, broken up by regions. :O
My eyes still bleed to this day!

Jax on July 8, 2008 2:48 AM

I strongly disagree with Jeff: I find code folding very easy for the same reason why I don't use a completely expanded tree inside the Explorer.

In my opinion Explorer sub-trees are collapsed to get a better overview and to find more easily the thing you're looking for. That's exactly why I use the #region directive.

NickB on July 8, 2008 3:05 AM

I agree. Its not nice to have a method folding ability when it folds the method and comments separately leaving you 2 folded things instead of 1 (the method with comments). I bet Visual Studio makers did method folding the easy way and didn't allow wiser folding, because wiser folding would have been so much harder to be implemented.

Silvercode on July 8, 2008 4:01 AM

Heh, I think I'm beginning to get the "smackdown model", some interesting comments have emerged here.


I've used regions in moderation in the past with some success, though I could take or leave it. As usual though, my opinions suffer from never having to have maintained a large project.


One place I used to use regions all the time was for properties, to wrap up the boilerplate getter and setter code. Fortunately that problem has largely been solved with automatic properties (and hopefully we'll see automatic backing variables in the next version of C#).


Several people have expressed a disbelief that you need to manually specify regions for code folding. The truth of the matter is that VS does quite a bit of automatic folding, though not to the granularity of most other editors. You can fold using directives, namespaces, comments (including XML comments), classes and methods (I might have missed some) but not things like conditionals and loops. Personally I've never had a need to fold at the level of individual conditionals and loops (if you do, it probably needs to be refactored) but I can't see it would be something terrible difficult to add to the IDE and it most likely has already been considered, so I wonder why it hasn't.


"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."

You can turn that off in Options->Text Editor->[Language]->Advanced->Advanced. I do think it's the wrong default though.


"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."

I think it may remember them in the user options file of the project, which tends not to be distributed or source controlled.


"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?"

I find XMLDoc comments incredibly useful, even for internal/personal projects. Remember if your using Intellisense the XMLDoc comments come up in the tooltips which, if you've not touched the project in a while can be extremely useful in remembering what a particular method does or one of it's bizarre edge cases. You can collapse up XMLDoc comments, though annoyingly there isn't an option to collapse them all at once.


"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."

Forgive me if I misunderstood but you can collapse to definitions (Context Menu->Outlining->Collapse to Definitions). It doesn't show just the public interface (Object Browser is good for that) but it makes it easier to see. Of course it doesn't play well with regions, as someone else pointed out.


"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."

Of course, Jeff has stated that he hates trees too ;)

[ICR] on July 8, 2008 4:13 AM

Wow, loads of comments.

I had to admit to being old school and not being a big fan of code folding. If you're working through somebody else's code then it breaks the flow of the code. I know it's hidden in plain sight but that's how it works for me.

To be honest a lot of the more complex code I've seen which is packed regions and comments and everything else could have been done with a lot simipler code.

Greig Harper on July 8, 2008 4:14 AM

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

Not really, you can put XML docs in a separate file and include them. Here's an example: http://www.codeplex.com/thehelpertrinity/SourceControl/FileView.aspx?itemId=2259&changeSetId=7821 (scroll down to the members).

What's necessary is a tool that manages all this for us, built right into VS. It's something I've wanted to write for a long time, but just never got around to it.

Kent on July 8, 2008 4:46 AM

"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? Long, horrible spaghetti code blocks?"

Perhaps you're doing the dirty job of maintaining someone's legacy code which looks like the afore-mentioned. In that case, it might be useful to close the code into regions that you can get out of your sight once you checked and double-checked them: "Here's that ugly hack from 20 years ago, I just made sure it has no side-effects on what I'm doing, so let's get those 500 lines out of the way so I don't have to scroll all the time".

Sure beats rowing the mouse wheel. Or imagine control-effing in vi! :)

Nikola Gedelovski on July 8, 2008 5:09 AM

I also disagree with the article.

Ivan on July 8, 2008 5:20 AM

With great power comes great responsibility. Like any language feature that can be misused (partial classes, delegates), some common sense needs to be applied. If a developer hasn't the sense to see that overuse of such a feature will cause readability & maintenance issues then you've got bigger problems within your team than you originally thought.

Andy on July 8, 2008 5:27 AM

I disagree. I think the author was using regions for the wrong reasons. On a scenario where multiple guys are working on the same file , this is a perfect way to ring fence your code. Working with just your region code expanded gives you the feel of working on a small chunk of code and savesyou from un necessary scrolling/searches.

Sree on July 8, 2008 6:13 AM

@<post> :

I strongly disagree. The ability to hide regions of code in order to underline others is a good thing. And Visual Studio can be configured to show them open by default AFAIK.

Andrei Rinea on July 8, 2008 6:21 AM

Sometimes I am forced to work in Centura/SQLWindows. I am told it was popular outside the states sometime in the 90's.

By default everything is folded and I mean everything. Every if, for, else, function, variable blocks.. That and the editor is not very discoverable, so while there probably is a un-colapse all hotkey I haven't found it yet.

It can be the most annoying feature ever if not implemented properly.

On the other hand, Netbeans collapses my code in a lot more friendly manner and finding the collapse all un-collapse all hotkeys was discoverable from the menu.

gruckiii on July 8, 2008 6:32 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),

It isn't just that. Emacs over the years has had support added for pretty much every text editing need a person could possibly have. That's a *lot* of functionality.

Nobody who sets out to create an editor from scratch (not even Microsoft) can possibly produce all that functionality when they are done. So the absolute best any other editor can shoot for is implementing a subset of Emacs. Some parts of that subset they may manage to implement a bit better, but it will still just be a subset.

Its true that occasionally these alternate editors do something new. However, any new functionality someone may come up with can just as easily be added to Emacs. If its useful, it will be done by someone. If its really useful, it will get moved into the default codebase.

So there's really not much point in anyone ever creating their own editor. I'm not upset that some people still have the hubris to do it, as the competition ends up making Emacs better. But that's all it is doing.

T.E.D. on July 8, 2008 6:32 AM

>> >> Your project is now full of crappy code that you can't see

>> I want to have this framed and put on the wall at work :-)

Will you settle for a motivational poster: http://img184.imageshack.us/img184/8929/72ve0ptu4iry6.jpg

wenke on July 8, 2008 6:37 AM

wtf. i thought it was standard behavior to fold code *automatically*. #regions seem to be some ugly hack. indentation and curly braces should give editor enough hinting to fold if requested by user. don't see how it fits to teamwork, as it should be editor-side feature only. if i recall correctly, even vim handles code folding quite sanely, without any special #regions or other crap. code folding also allows you to have clear overview of a class or other code.

zokier on July 8, 2008 6:46 AM

Jeff, yes!!! vim & probably other editors too have very very advanced folding / marking / navigating features. That stuff in your post is rediculous.

Ian on July 8, 2008 7:14 AM

for vim you have folding by complex expression based on the language, by indent, by other things, and those expressions are already made for basically every programming language out there, no one should be manually marking fold locations in code.

Ian on July 8, 2008 7:18 AM

Agreed. Regions are not anything I've personally found interesting or useful. I'm constantly stripping them out of generated code.

Mike on July 8, 2008 7:25 AM

Visual Studio does automatically fold pieces of code. Functions and block level.

Regions just allow you to declare custom fold points with names.

So please people, don't think Visual Studio doesn't do other code folding that doesn't require Regions, because it does.

Nik Radford on July 8, 2008 7:36 AM

I do not agree. I see your points, and I acknowledge them, but my personal experience is that folding (with vim) improves my productivity.

Indeed, I take care of adding folding tags as much as I can, because I prefer to keep control of the folding level. I do not like having to unfold every indentation, that makes code navigation very hard. I do like having folding at the routine level. It makes my navigation and my cut-and-paste very easy. If I want to delve into the details of a routine, then I unfold it with a single hit of spacebar.

I think it's a matter of taste, but to me, folding increases productivity so much that I install vim 7, if I don't find it on the system, just for folding.

Stefano on July 8, 2008 7:40 AM

#region Important Stuff
_foldingIsGood = true;
_jeffAtWoodIsWrong = true;
#endregion

Keith on July 8, 2008 8:03 AM

@Keith try something like:

#region Private Methods
public WtfEnum AreRegionsBad()
{
WtfEnum result = WtfEnum .No;

switch (coderType)
{
case SensiblePro:
result WtfEnum.No;
break;

case Hacker:
#region nasty
result = WtfEnum .Yes;
break;

case Noob:
#endregion
result = WtfEnum .FileNotFound;
break;
}

return result;
}
#endregion

#region Public methods
private bool FoldingGoodButRegionsOpenToAbuseAndMistakes()
{
bool result = true;
#region Irrelevant logic
result = false;
#endregion
return result;
}
#endregion

Graham Stewart on July 8, 2008 8:23 AM

I haven't noticed if it's been said, but VS has plenty of automatic code folding features, WITHOUT using regions. Regions allow further, more programmer defined folds to be created.

VS even let's you use code folding on other file types like HTML, XML, etc... (uh oh, here comes the XML debate again)

HB on July 8, 2008 8:30 AM

I use regions to prevent my boss from touching code that he doesn't understand. If he actually opens that code, then his head will explode, and, headless, he will start breaking the code in subtle ways that take days to unravel.

So my regions normally look like this:

' This region contains all the drawing code for this control.
' Do not edit this code unless you take the time to understand it.
' WARNING: This code is very complicated.
' Small changes may have effects that are not immediately visible.
#Region "Drawing and GUI Code - Do Not Touch!"
...
#End Region

This usually keeps our code safe ... usually.

I also use regions to hide lists of private variables and public properties.

Evan on July 8, 2008 8:40 AM

Jeff,

I wholeheartedly disagree with you. Between this and your preference for ...

if (someString == "")

over

if (someString == string.Empty)

... I'm beginning to have my doubts on your content.

Randall on July 8, 2008 10:07 AM

from Graham Stewart post
The worst thing that I saw in your post was cases. Using cases inside of classes can cause BIG problems in VB when integrating with certain visual objects. Honestly I have no idea if this is true in C# or not, being that My C experience is in C++.

Mark on July 8, 2008 10:39 AM

Sorry Jeff, you are wrong on this one, but not for all the reasons above.

In my world, we receive massive XML (and custom) data files from other companies. We don't dictate the format/schema, and only rarely can we convince them to change it from whatever absurd raw format they wanted to send us in the first place.

Imagine a health-care-related XML file with ~500 data elements logically grouped like this:

<physician>
<lname>
<fname>
<group>
<address1>
<address1>
<city>
<state>
<zip>
<specialty>
<taxid>
<healthplanid>
<upin>
<ac>
<phone>
<faxac>
<fax>
</physician>
<hospital>
<similar data to physician>
</hospital>
<patient>
<similar data to physician>
</patient>

etc. These are manually loaded using C# because address1 can be blank for the physician but not the patient, whereas the <zipext> can be blank for anyone but the hospital. Also, each individual element has its own rules for different companies, different error messages that must be shown, and about 5 years worth of custom, client-specific enhancemen...err, hacks to get around random stuff they send to us.

With code folding, we can group hundreds of lines of code like this:

[-]#region physician
// CrazyClient42 can send us data without a physician <lname> tag
// CrazyClient18 can send us an empty or "" <lname> tag
xnTemp = IncomingXmlDocument.SelectSingleNode("//Root/physician/@lname");
if(xnTemp == null && client != "CrazyClient42")
throw new exception("Missing Physician Last Name");
if(string.IsNullOrEmpty(xnTemp.value) && client != "CrazyClient18")
throw new exception("Empty Physician Last Name");
PhysicianDataStructure.lname = xnTemp.value.trim();

... repeat for every data element in <physician>...
#endregion

[+][#region hospital]

[+][#region patient]

If there is a problem with the XML file loading, we need to stop immediately and halt the process with the appropriate message. Using these regions has saved us countless minutes looking through hundreds of lines of similar-looking code.

Can you put these in their own functions instead of regions? I guess you could...you could even put them in their own files if you wanted to. You could put them in their own DLLs! But why? They really are all part of the same function: loading a given XML document, baby-sitting it every step of the way because you have to and storing the orderly data in a set of known programming structures.

Rick Scott on July 8, 2008 10:55 AM

I've always wished for a way, when browsing a class, to hide private methods/fields of that class. So I like #regions.

Ultimately though I'm in the "format the crap out of it" camp. We've been coding in plain text for too long. I want an IDE/language that treats code as a database, and lets me view functions, apply my own (not checked in!) tags, formatting, and organization. I want to be able to use rich formatting to, say, paste pictures in as comments. But most of all, I want to use the <blink> tag IN CODE. :)

Mason on July 8, 2008 11:11 AM

I think it's useful to be able to organize code using regions. I want to hide stuff I'm not working with, scrolling up and down becomes tedious and icremental search does not work unless you want to keep remembering the name of every method, class etc.

Patrick on July 8, 2008 11:50 AM

This is why I prefer editors like Vim (GVim for you Windows people).

I can control whether folds exists, how deep they go, where they start and stop and much more.

Brett on July 8, 2008 12:46 PM

@Rick Scott: You could create some more elaborate way of doing things, like encapsulating search logic and exceptional situations, use object oriented programming and inheritance etc. That way there would be actual structures instead of hack regions.

When I design and program software, I can see all objects in my mind. So lets say I want to access the logic of CrazyCustomer33. I would know that it is in a subclass of parse logic eg. in ParseLogicCC33. So I just open that class instead of starting to search through hundreds or sometimes thousands of lines of code.

Silvercode on July 8, 2008 12:51 PM

I'll have to back up the VI (VIM) comment above. VI has great code folding. You can specify how it folds and tell it to remember your folds open/close when you come back to the file later (plus remember where your cursor should be).
Hard to be the efficiency of VIM if you know your language.

j-man on July 8, 2008 1:08 PM

Thumbs down

Just use that hot key you mentioned to expand them all and pretend they're "comments" (they are comments!)

privatehuff on July 8, 2008 1:51 PM

This is ridiculous. How could clearly defining the elements that make up a class be bad? If every class that is written had regions for:

Private Members [or Fields, or whatever]
Constructors
Properties
Public Events
Private Events [think WinForms]
Public Functions [or Methods]
Private Functions [or Methods]

... then it's crystal clear where to find the code you are looking for. Someone reports a bug when they click "Update" in the customer screen of a web app or WinForm app? Well, go to the customer web page/form and look at the .Click event of the button in #region "Private Events". There is a problem with saving the data of a customer to the database? Look for the .Save method in #region "Public Functions". How could anyone not advocate a cleaner, logically laid-out code base, where ridiculous scrolling is not required?

HardCode on July 8, 2008 1:52 PM

@Silvercode:

We've gone down that route before, and it makes changes more difficult.

There's nothing easier then simply putting the code exactly where everyone would look for it first.

We have pre-programmed regex searches that look by client name and those serve perfectly if we have to know if a particular client has a particular hack turned on at a moment's notice (like on a conference call).

Complicating a long series of very simple lines of code is not an improvement.

Rick Scott on July 8, 2008 1:55 PM

@Mark: "from Graham Stewart post The worst thing that I saw in your post was cases.."

Huh?? You might want to practise your code review skills!

There is a public method in the private methods region.
A private method in the public method region.
Folding the "nasty" region makes it look like Hackers get FileNotFound.
Folding the "Irrelevant logic" makes it look like result is true.


And I think I'll carry on using switch/case statements in my code. :)

Graham Stewart on July 8, 2008 2:48 PM

Late to the party and didn't read all the comments but still...

I don't get all these negative comments. Especially those that say other IDE's (eclipse?) do it automatically. That means you are using the tool wrong.

tasks for your IDE (in some tree for example or whatever):
- Group members by public/private
- ordering members on name
- mark your constructors
- fold each function separately (if you really want to do that)
- separate list of properties and functions
- ...

that is all technical.

But good luck letting your IDE group functions based on businness logic. It just can't.

Regions also will not make those decisions for you. So the hard work is still yours (yes it can get complicated it larger projects). But at least now you have something to work with.

Tim on July 8, 2008 3:42 PM

> icremental search does not work unless you want to keep remembering the name of every method, class etc.

Yes, god forbid we actually remember the names of the routines and variables we use..

@wenke this is awesome!

http://img184.imageshack.us/img184/8929/72ve0ptu4iry6.jpg

Some final points as the discussion winds down:

1) I personally find the way Visual Studio handles default folding to be completely unsatisfactory bordering on useless. It is entirely possible other editors (Vim, Emacs, Eclipse) handle this in a more rational way. I agree that lots of optional folding can and should be done exclusively by the editor.

2) Folding doesn't kill code, Programmers kill code. Yes, it *is* possible to use folding in a rational, sensible, restrained way. It is a pity that I almost never see it used that way in the Visual Studio ecosystem, though. It's typically what you see pictured in the blog post.

Jeff Atwood on July 8, 2008 4:05 PM

In defense of regions, when you are doing code reviews or presentations, I find it helpful to use regions to focus your audience's attention on one set of code at a time.

On CodeProject there is a set of macros that automatically adds regions and comments around procedures (ctrl-d), and opens/collapses all regions (ctrl-shift - / +). It's one easy route to go if you like regions as I do.

(Alt-ctrl-j) in R# is an awesome way to add regions as well...

I don't think it's a code smell, because regions are soooo easily opened through VS or macros... And you are using resharper to develop right? It's really a crime not to, as those light bulbs R# provides can really be helpful for tightening code (and regions certainly doesn't hide those errors or suggestions - though a pragma will).

Just my $0.02,


Jonathan Starr on July 8, 2008 5:30 PM

Wow. The asininity of some of these comments is astounding. Code folding hides things and groups things, yes, BUT THAT'S WHAT CLASSES ARE FOR. What Jeff is saying is that if your classes are so long that you need to fold them, YOU SHOULD REFACTOR THEM TO BE SMALLER. Need to group business logic? Pull that shit out into a separate class. That's what I meant by code smell - if you're tempted to use #regions, consider whether you should be creating a new class.

I understand that sometimes you're stuck with legacy code, but try to take some time to refactor that shit first, if at all possible. At the very least, put your new logic in a new class and call it from the old code. Anything else just exacerbates the problem.

John on July 8, 2008 5:59 PM

Two points. The argument that regions are all most developers will ever see because it's the default seems nuts to me. It seems utterly reasonable to expect a professional coder to set the preferences of Visual Studio. They are programmers. It's one thing to expect non-technical users to accept program defaults because they don't know enough to go set preferences. That's a poor excuse when it comes to professional programmers. Secondly, regions are not code written to accomodate the editor; they're written to accomodate the coder. Overall, this seems like a fairly shallow complaint. Set your editor the way you want things to look and get over what other people prefer in their editors.

Spitzen on July 8, 2008 6:29 PM

The underlying problem with using #region for anything other than what it was designed for (hiding auto-generated boilerplate) is that it is not in any way understood or checked by the compiler.

So whatever scheme you have can't ever be relied upon when you actually need to read the code to find a bug, drill down on one particular area. Put your public methods in the 'private region', your event handlers in the stubs region, the compiler won't care. Put your 'customer99-specific' code in a function or class, and you can be sure a change to it does not change the behaviour for customer-74. A region, all bets are off.

If your code is bug-free and perfect this is not a problem. But the more 'real-world', pragmatic, rushed and buggy your code is, the bigger a problem you have.

soru on July 8, 2008 7:01 PM

And I don't have to use regexp searches to find things. I just open the class ParseLogicCC33, because I know they the logic is there.

How everyone could know that the logic is in ParseLogicCC33 instead of being in a region? Well, you have a design of the solution. It should have a class diagram. This is the right way of doing things anyway. You design first, then implement. Everyone who has to touch the code should first look at the design, because otherwise its more like guessing or figuring out on your own or with your coworker.

So you have the design and a class diagram and its easy to take a glimpse of that and see where all the logic is. After that no more regexp searches.

Surely hacks work if done right, but I don't like the idea that most stuff is made by weird hacks that are called solutions that "everyone" "understands" when there is even no design documents. One thing leads to another and soon the whole system is full of undocumented hacks.

If regions are used, there should at least be programming conventions for them.

Silvercode on July 9, 2008 12:16 AM

#region My Opinion

I use #region - so sue me! I think this is a non-issue, and your rant amounts to little more than whining.

That said, I completely respect your right to think differently. :P

#endregion My Opinion

Jason Bunting on July 9, 2008 12:26 AM

Overused #regions suck. That's why some people (self included) hate them.

They're fine when they hide visual noise. They suck when they hide information.

Joe Chung on July 9, 2008 12:32 AM

Actually, Eclipse has this option also (fold methods and inner classes) without any #region thing, and I find it very useful when navigating the code base searching for bugs. It also helps me from getting my self into trouble. I mean it, if you're doing some task and while rolling down the code you find some stupid comment, you laugh and break your concentration. Or even worse, you find stupid code and by the time you get to add your stuff, you're actually thinking: "Who made that crap?" or "Maybe I can apply some Spartan programming there" and there goes your "zone".
Good article thought, you've got to keep up with your opinions

ubersoldat on July 9, 2008 6:25 AM

"criminally overused in practice and heavily prone to abuse": Absolutely yes. 100%.

Show the meat. Hide the fluff if it really helps, but *please* don't hide things to rote.

One-size-fits-all approaches always end up hiding what you really care about. And if your class is so big you need to organise it 'like chapters in a book' then for your own sake refactor it.

[Today's smackdown seems to have struck a nerve, yes?]

piers7 on July 9, 2008 8:40 AM

I love regions. If I'm writing something long and winded, I can put pieces in separate regions and find them easier.

#region Structures
...put all my structures here
#endregion Structures

Let's say I have a page of structures. I can fold this and I don't have to look at them. When I look at my file, I see what I want to see. If I want it all, I do CTRL-L.

Just FYI.

I always name both sides of my region. Also, if you want to find the other end of a region, put the cursor on #region and hit CTRL-]. This works for squiggly-brackets too.

Visual Studio.

Dan7el on July 9, 2008 9:48 AM

have to respectfully disagree.

#region puts good use of code grouping, where I put the methods in relative segments (like private and public attributes). This grouping also enables me to navigate to the method I'm interested in faster.

Althrough, it's given that the regions need to be properly named in order for this to work.

Andy on July 9, 2008 10:03 AM

To think the IDE should be responsible for grouping (with #region) Constants, Properties, Constructors, etc, together also assumes that all programmers organize their code in the same manner. I think people start forgetting that the way we use our IDE isn't the same as the next guy.

Not everyone is going to organize their code in a way that can be predicted by the IDE. Regions seem to be a rational, flexible way to allow people to organize (or not) their code aside from the automatic folding already done.

HB on July 9, 2008 10:13 AM

Yea, I hate it too, nothing like coming up with another way to hide something that should not be hidden...

Mac on July 9, 2008 10:36 AM

Jeff I love your stuff, but of all the lines to draw in the sand on coding practices, in my book this ain't one of them. The mere presence of a region reflects at the very least an "attempt" at code organization, and that is not a bad thing.

Brian H on July 9, 2008 11:23 AM

Whoa, good to hear that someone as well respected as Jeff also can get all the same crap about regions I received on my blog post: http://blog.codedemora.com/2008/02/29/just-say-no-to-c-regions.aspx

Saul on July 9, 2008 12:11 PM

It seems the #region was your first wife that left you for you bset friend.
Couldn't you find 50 more reasons why not to use #regions?

#regions is a great thing. Period.

Charlie on July 9, 2008 1:04 PM

folding is simply natural for c#. could not say that for c/c++ or f# or any other from top to bottom language.

Danijel Kecman on July 9, 2008 2:10 PM

God bless you, Jeff! Would that every programmer in the world would read your blog and put your words into practice!

Aaron on July 9, 2008 2:52 PM

i like code folding. when working with long code, it is very handy (to me, at least) to be able to just fold up the parts that i dont need to look at. Even when folded, search will still find stuff in folded code..

i'd much rather open a piece of source and see the fold comments denoting the different sections. This (in my opinion) is not only a form of documentation but also a high level organization tool. Even more so in team environments.

It sounds almost like the writer of this article is one of the 'cowboy coders' that they complain about at the top..

That's just my 2 cents..

scott on July 9, 2008 4:33 PM

@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.


NO! Use #regions to aid model-driven software development, and use #regions to separate true concerns that can't be identified by a tool, because you've yet to set-up an explicit open-closed interface.

John "Z-Bo" Zabroski on July 9, 2008 6:08 PM

I think #regions is a personal preference, some people like to see all the code they have, even though it's 10,000 lines. Some people like to hide the contents of methods/functions they have written when they are done with it. I'm with the latter group.

When I'm done with a function, I hide the content of the function, leaving the function name and comment intact. The comment + function name should be enough to easily work out what the function does. If it's not, you are a messy coder. There really shouldn't be a need to see the content of a function when you are done with it.

http://img234.imageshack.us/img234/8783/picture3xe9.png <-- how I usually do it

Thomas Winsnes on July 9, 2008 7:40 PM

I like regions too, but at the same time I don't like them. Maybe its like using goto. Its handy, but not recommendable. So people use regions until it is taken away from IDE:s. Period. But is regions really as bad as goto? Well, it depends. If you are not capable of living without regions, you will not see why you shouldn't be using them and you think everything is just fine.

So I said that I also like regions. Would I use them? In some projects many classes are so big that I would use regions for the sake of clarity, unless I would have time to refactor the classes. Also I might first add regions, because that way I would see what parts need further refactoring and redesign.

But here I see again that thinking programming hits and designing is left back somewhere. So there needs to be more effort put into actually designing and modeling the program so less regions will be needed.

Silvercode on July 10, 2008 12:42 AM

I concur wholeheartedly.

#Regions are just one more M$ attempt at dumbing down the software community. Okay maybe that's a bit paranoid of me and someone actually thought they would be beneficial, but still. My IDE should help me, like say, trusty ole R2-D2. It should not baby me like Dr. Spock.

Mattkins on July 10, 2008 6:22 AM

I have little problem with regions. They could be useful. I'll tell you what I do have a problem with, and it is those F$#*@ tiny expand/collapse icons! They must have talked to Adobe cause those are other idiots who insist on having to click a 2x2 pixel area. Regions would be nice if there was some decent region management. I.e show/hide/collapse attributes,regions,intellisense and frankly I'd be a happy camper. And do away with those stupid rectangles around collapsed parts.

I was once going thru some 3rd party code where it actually made sense but it is either all or nothing here. You can expand everything easily enough but cannot collapse only certain parts.

Personally I don't use regions, they piss me off because they're completely unmanageable. When collapsed it is a gray frame bonanza and when expanded they create codefile garbage.

Ron Stout on July 10, 2008 7:43 AM

Every time I read a post on this blog and the comments associated with it, I am reminded again how lucky I am to not have to code with Windows anymore. 3 years ago, I switched off Windows + Windows programming after ~12 years doing it for money. Since then, every time I'm exposed to Windows coding, I'm sort of shocked like "wow, they keep falling farther and farther behind."

I don't mean this as a holier-than-thou comment at all. But honestly, I feel very fortunate that I don't have to deal with any of this stuff. MSFT elected to create a keyword for code folding? Really, when free IDEs do it automatically?

And the platform + tools are still encouraging people to minimize the number of source files they have, like it's 1990? It makes sense that if Windows can't efficiently handle lots of files, then you want all your code in a single file. But wow, I had no idea it was still this bad.

I know everyone can't switch off Windows and still keep the bills paid, but I'm glad I have been able to. Good luck to you guys.

RG on July 10, 2008 1:13 PM

A provocative idea, and after thinking about it, I partially agree. If regions are used to mask "dirty" code you are ashamed of, then you shouldn't use regions. You should refactor.
On the other hand, I find regions useful in illustrating what the class is about. I tend to use lots of private helper methods: these are prime candidates to go to a region. Don't expand the region, and you have the high-level view of what the class is about, without clutter. Expand the region, and you can go into the nitty-gritty of the implementation.
That being said, partial classes are an interesting alternative to regions. If you want to isolate a specific group of behaviors, put it in its own partial class.

Mathias on July 10, 2008 1:49 PM

I disagree with you on this one. Kudos to you on making your point though. I certainly don't have to agree for the point to be valid. Anyhow, like anything else regions can be used poorly and that is a shame.

jride on July 10, 2008 2:09 PM

@RG

Rather than sounding "holier-than-thou" as you put it, how about trying to sound "intelligent" or at the very least "informed" before commenting? It's been stated multiple times already that code folding is integrated into the IDE and that "regions" are optional.

HB on July 10, 2008 2:34 PM

Weak post. Regions are fine. Anything used excessively is a pain...

Chico on July 10, 2008 4:55 PM

Regions are a lazy trick to allow some "organization". IMHO the future is in storing everything in binary intermediate language that doesn't lose anything but always runs rather than is such a fragile thing as a text file. eg. Think Spore procedural creatures stored in .png where the image is the sum of the parts in the creature. You see IDA Pro disassembler and latest movie production software doing something along there lines.

The IDE, language and the result to need become much, much closer together so when you are programming you are editing and seeing the end result - immediately! Think of creating levels in a game editor built into the game engine or painter painting. The moment you write the code and hit, if it's ok, it takes effect and is immediately in the latest version of the binary. Version control, testing, specification etc is built into the system of course to kill problems errors before they get anywhere.

zzz on July 10, 2008 8:48 PM

Code Folding: The first IDE feature necessitated by a bad object declaration design.

NickHodges on July 10, 2008 10:36 PM

C# Regions are a CodeSmell

There is a second use of Regions - hiding portions of a method. To any agile developer, this would immediately tell you that the method is too long. But I see the practice time after time. So much that I wrote about Regions as a CodeSmell.

<a href="http://aspadvice.com/blogs/rbirkby/archive/2008/05/12/Code-Smells-in-C_2300_.aspx">http://aspadvice.com/blogs/rbirkby/archive/2008/05/12/Code-Smells-in-C_2300_.aspx</a>

RichB on July 10, 2008 11:29 PM

Regions are great. Sometimes when you're working with awful APIs you can't avoid excessively long code where often there's no need to overfragment the code into unneeded functions and files.

I agree with some of your points, but i have the same opinion of comments. I hate how unreadable comments make the code.

Bobby on July 11, 2008 5:37 AM

I use them for code that shouldn't be run, due to a change in requirements but may have to run again soon due to the requirements reverting back. I wish people could make their minds up :p

Mr. Tidey on July 11, 2008 8:17 AM

You should write a post about the evils of classes. Who wants their code hidden in a separate class? Someone with something to hide is who. If you are a truly excellent coder you'll throw information hiding to the wind and just put everything out there in one place. How am I supposed to see it if someone organizes it into manageable sections?

Publius on July 11, 2008 9:11 AM

I have two words for you: Baby and Bathwater.

Among other things, you seem to imply that once code is placed inside a region it is no longer accessible! No, you can't SEE it, but even if it were expanded, you probably wouldn't bother LOOKING at it unless you thought that's where a problem was. And the region will automatically expand while in debug mode, so it isn't like the environment is HIDING anything from you. So why not get it out of the way when you KNOW you don't need it?

When you clean your house and put things into your closet, you can organize things neatly or shove the things in there with no thought. But should closets be done away with just because some people use them to hide junk? Should organized people have to forgo their use so that messier people will be required to leave their slop sitting out for the world to see?

Anything has the potential to be abused. Regions are no exception, but I code more quickly by using them without any of the detriment you decry...and I'm sure I am far from the only one.

Mr. Scott on July 11, 2008 12:47 PM

Personally, I like regions... I agree that there are occasions when knowing which region to open when looking for a method is a pain. However, there are:
1. SEARCHES
a. Ctrl+Shift+F - Find across project / solution files
b. Ctrl+I- Incremental
c. Ctrl+F - find within file
2. The method-name / property drop-down list at the top of each code tab
3. GOTO DEFINITION
4. FIND ALL REFERENCES

In fact, the number of times I find myself looking in a file just to browse it is so minimal it can be discounted. I am just about always looking for soem reference that one of the searches above has found.

I also consider regions (when used 'how I like to use them' <big grin> to have a useful side-effect - it makes me think about the intended audience of the code, and how it will be used. If it's public, I need to consider the caller and interface considerations etc - perhaps CLR interop is a consideration etc., but if its private perhaps I can pass around different types, etc. The region can be a marker to remind us to think about these things.

However, having said all that, where I currently work regions were historically used as an ALTERNATIVE to methods / functions even (you know, the two-thousand line method with twenty regions in) - which I can assure you I do consider to be total and utter misuse of regions :(

Nij

Nij on July 12, 2008 4:36 AM

I have to agree and disagree. I personally love to use regions to organize my code according to implementation until I started to use the custom tool used for generating a plugin template for our project which totally abused the use of regions. A region was created for each object declaration (method, fields, properties, namespace, etc...) in the IDE. That is totally sick.. i'd have to unfold multiple times for a 'public bool foo = false'??

Anyway.. same with most here, regions, if used properly is undeniably good.

Stynx on July 13, 2008 4:47 PM

Eric Gunnerson, one of the MSFT engineers who was involved with C# development for a long time, agrees:

http://blogs.msdn.com/ericgu/archive/2008/07/10/region-sliced-bread-or-sliced-worms.aspx

Len Holgate calls it #herebedragons

http://www.lenholgate.com/archives/000400.html

Jeff Atwood on July 13, 2008 5:07 PM

I personally like regions for breaking code files into groups of members by construct type (like chapters in a book) and went so far as to create a tool to automate doing so. NArrange will group members into regions and can also apply sorting by name, accessibility, etc.

http://narrange.sourceforge.net

However, I realize there are many downsides to regions and that not all teams condone their usage. Thus, the most recent version of the tool allows you to apply grouping and sorting of members without region directives. See Daniel Root's post for more info:

http://blog.lifecycle-solutions.com/NArrange++Take+2.aspx

Also, for those just looking to strip regions out of code, this may be helpful:

http://www.codeproject.com/KB/codegen/narrange.aspx?msg=2579903#xx2579903xx

James Nies on July 13, 2008 10:24 PM

Jeff, I'm totally with you.
Reading through all the comments I can't believe how many developers think that #region is OK. It's (almost) always a substitute for good factoring, and definitely a code smell.
This was my post on the subject a few weeks ago:
http://stuartharris4.blogspot.com/2008/06/c-regions-inline-comments-and-blank.html

Stuart Harris on July 14, 2008 3:57 AM

Disagree.

Visual organization goes a long way in my book, and code folding is another tool for doing so. The folded sections give me an overview of the groups of methods (public, private, events, interface impls, etc.) in the module. When I open a code module, I first hit Ctrl-M-O to collapse all regions, scroll to the region I'm interested in, then Ctrl-M-M to expand that region. I can then browse all methods in that region by signature. Additionally, I organize my methods alphabetically by region, so finding a method is even faster.

I'm definitely a fan of code folding and relish the relief from page after page after page of code when I have an idea of what I'm looking for. If I know exactly what I'm looking for, I use the search tool, but otherwise I'm a browser-navigator when it comes to code.

Craig Boland on July 14, 2008 8:29 AM

folding in general looks like a weak version of literate programming. Which, given your opinion of folding, you'd really hate.

Shawn on July 14, 2008 4:10 PM

The #region directive is useful when you write big classes: controls or web service classes. In case of these, splitting them in smaller ones would lenghten and/or complicate your code. In classes which are shorter than 2 pages the use of the #region directive is silly.

Jeno on July 15, 2008 8:20 AM

I have to disagree.

When inheriting legacy code in +1000 lines, and no logic ordering. That's a headache.

I must agree though, VS 2003 does not expand regions properly and can be a pain at times.

That said, I would rather see the outlining logic before jumping straight into any programming.

Bywin on July 17, 2008 1:07 AM

a good developer can adapt to any working environment:
http://www.dotmad.net/2008/07/good-team-developers-are-cameleons.html

dotmad on July 17, 2008 8:42 AM

100 years ago, some physicians said it was impossible for an object more weighted than air to fly. They were SURE it was impossible. Today, we just smile...

When can we you be sure about the right direction of progress? I mean: Regions really can't fly? Are you absolutely sure? Block diagrams also hide information; however, they can fly. Are regions like elephants trying to reach the sky by waving thear ears?

Whatever will be, will be.

Thanks for shaking our neurons, Jeff

oscar on July 21, 2008 5:56 AM

I use them, I like them.

No, I don't use it to "hide" anything, just to give myself a cleaner working surface to work on. I'll typically place public methods in one, private in others, if applicable event handlers in a different one and so on and so forth (precisely as in the sample code shown).

If I am working on redefining a class' public interface, I may not want to have all the private methods "get in the way" when I scroll through.

You want to use incremental search... sure... but what if I don't know what the heck I am looking for?

I think the point you are making has some validity to it as it relates to the tangential points you make (bloat, maybe separation of concerns somewhere in there, etc), but come on... but you have to admit it is highly religious, as in you were high on a horse and had some adrenaline flowing when you wrote this...

Not all opinions are truths, nor all of those absolute. regions have their place, here and there and some people certainly abuse and misuse them, but as much as any other "tool" they all step in to aid the "smith" feel more comfortable in the exercise of his trade.

I like them, I don't *love* them or swear by them, but I certainly don't mark them with the scarlet letter like you have done here.

Guillermo on July 22, 2008 10:26 PM

Hi,

After a zillion comments, no-one is probably going to read this one. But I happen to agree with Jeff here. I hate the regions because I can't see the code and so can't as easily browse it and get a feeling for it.
(And for seeing an higher level view of the code (which is what most people seem to do with folding), I mostly use a plugin called ModelMaker code explorer, it shows the structure of the class in a separate tree next to my code.)

Tjipke on July 24, 2008 12:14 PM

Wow.

It seems to me that since you ventured out on your new project and the cash might not be flowing as easily as it was before you've just been picking the most religious subjects and getting on your soap box about them. If you need the page rank up so that you can get more click throughs that badly Jeff I'm sure someone can sub you $10 til pay day.

It's starting to border on drivel, it really is.

Carl on July 25, 2008 4:53 AM

One more helpful hint, specifically for those who are forced to work on a team enamored of regions (this is cobbled together from a couple of sources online):

Sub CollapseToDefinitionsButExpandAllRegions()
DTE.ExecuteCommand("Edit.CollapsetoDefinitions")
DTE.SuppressUI = True
Dim objSelection As TextSelection = DTE.ActiveDocument.Selection
objSelection.StartOfDocument()
Do While objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
Loop
objSelection.StartOfDocument()
DTE.SuppressUI = False
End Sub

Instead of setting Alt-Left to "CollapseToDefinitions", you can set Alt-Left to this macro, which will CollapseToDefinitions, then expand all the regions. You get your nicely collapsed code...but now you can *see* it. The annoying regions will still be there, but at least now they won't get in your way as much when you're trying to work.

Enjoy!

Kyralessa on July 25, 2008 11:30 AM

I have to agree for the most part with what you're saying about Code Folding, I hate it and it seems a deceptive practice.

However recently I have been folding one specific section of my programs, the import sections. I normally have roughly 20-30 lines or more of simple import commands, which my IDE (Netbeans) handles automatically

Simon on July 28, 2008 9:36 AM

Jeff! Yes, finally, someone with common sense. I _AGREE_ WITH YOU.

Regions are to be banned. Even good coders get tempted, while bad coders, of course, litter their code with it.

I actually propose to #region out the coders who use #region. Inside a nice (dark of course) cube section. The problem would be that with all the regions they would use, they wouldn't see their desk, their chair and their lamp... Who cares, they can't see their code.

Max

Max on August 5, 2008 10:18 PM

I have to say I agree with Jeff on this one. When I first discovered #region, I thought 'oooh, cool feature', but I soon discovered all the deficiencies he talks about. So I moved on to more productive activities.

But I did find one use for them. Delving into the intricacies of - wait for it - Windows .INF files, specifically TEXTMODE.INF, which you will find on your Windows setup CD, and which is thousands of lines of impenetrable crap. But (and here is the saving grace) it is broken up, somewhat at any rate, into sections, so what I did was pre-process the file with an AWK script and insert #region directives around each section. I could then use the Visual Studio editor as a kind of outlining tool. It helped me a lot, and maybe this post will help someone else out there one day.

Paul Sanders
www.alpinesoft.co.uk

Paul Sanders on August 7, 2008 3:59 PM

Which do you prefer?

public void Init()
{
initA();
...
initZ();
}

public void Init()
{
#region initA
#endregion
...
#region initZ
#endregion
}

brank on August 8, 2008 7:31 AM

I have to say I agree with Jeff on this one. When I first discovered #region, I thought 'oooh, cool feature', but I soon discovered all the deficiencies he talks about. So I moved on to more productive activities.

But I did find one use for them. Delving into the intricacies of - wait for it - Windows .INF files, specifically TEXTMODE.INF, which you will find on your Windows setup CD, and which is thousands of lines of impenetrable crap. But (and here is the saving grace) it is broken up, somewhat at any rate, into sections, so what I did was pre-process the file with an AWK script and insert #region directives around each section. I could then use the Visual Studio editor as a kind of outlining tool. It helped me a lot, and maybe this post will help someone else out there one day.

Paul Sanders
http://www.alpinesoft.co.uk

Paul Sanders on August 8, 2008 2:27 PM


Wow!
You sure know how to make a big deal out of anything.

Personnaly I don't user coding folder because they are no use to me, but when working in a team each member must make small consecession on coding style in order to work.

I work once with a team that as for stantard to use code folder to group class members by type. Their claims was that it help organize the code base. I have enought dicipline to organize my code with out it, but I understand that other on the team might need a little push. So in modify the item and project template under the IDE folder the that the #region where added automaticaly whenever I create a file.

I totally agree with the fact that we should ask for better tools, but I think that we must first learn how to make the most of what we have until they comply. For those of you who don't already know it already VS have 3 navigations tools that allow you to group by member type, member access and alphabetical. The object viewer, the class diagram and the class view. My favorite is the class view because you can easily dock it on the right with the solution explorer, that way I can see the code can use the class view to navigate.

Their was an argument about sweep code under the rug. That might be true, but if experiences thought me anything is that even if the bad code is visible for everyone to see it doesn't make much a difference. Let face it when you are in some else code you are must likely to doing some maintenance work and all you want is get in, do your thing and get the hell out. Their is always the code review / refactoring and if you lucky the managements actually give time for that but with time to market kind of pressures that is unlikely.

Anyway it have been fun to read you Jeff.

Alexander on August 15, 2008 4:34 PM

Some comments above about how other IDEs already have automatically-generated views which group and sort in various ways.

Well, now Visual Studio 2008 has the same thing:

http://www.codeplex.com/ora

(Free, open-source add-in)

Daniel Earwicker on October 14, 2008 4:06 AM

This may be useful to some people:

\#region .+\n:Wh+\#endregion

Should find empty regions in your code. What you do with them is your choice, but when VS is adding them and they are empty it seems to me that there's a lot of things you could replace them with that would be more useful. Empty space, for example.

Breakfast on November 19, 2008 7:34 AM

I use grouping to ... group code that work. I don't use i a lot but some of the code are familiar stuff and can be tugged away when it works i.e. the code I have for docking a form. In my tiny mainform there are 8 methods that handle the task of docking forms. It works and need no further attention so it is grouped. It furthermore tells my colleagues what the grouped code does. In that respect I find grouping a good thing.

henrik carlsen on November 25, 2008 4:17 AM

what a load of crap. Cold folding is very useful for keeping code you don't need at that time hidden, and organising related code into sections.

dan on February 16, 2009 1:37 PM

cold* xD

dan on February 16, 2009 1:39 PM

code* I mean ... *embarrassed now*

dan on February 16, 2009 1:39 PM

I use VIM. At this point "REGION" CODE FOLDING ROX - since some languages does not allow splitting code into parts (files or anything like it). What is the best is that it is configurable how it works.

I have to maintain unreadable some code made by other people. The code (C#) has regions. It has other "cool" features like huge (>3000 lines) files, meaningless names (variables "tmp1","temp2", methods "doStuff","doOtherStuff"), nested IF's (I need to use horizontal scroll-bar frequently), hard-coding, empty "catch" blocks, and many more. "REGION" CODE FOLDING SUX.

Adderek on March 8, 2009 2:44 PM

I couldn't have put it better myself Jeff. Everyone who disagrees with what you said is WRONG! There are so many unintelligent pov's in the comment here it makes me sick! These people might as well just print up sheets of there code and piss all over them before handing it off to their coworkers.

Anonymous on March 30, 2009 1:22 PM

I completely agree with you post. Regions are ugly/obfuscating constructs which should be considered a code smell. Interestingly, its the senior devs (not by age, but by competence) in our team who hate them and the juniors who love them..

anonymous on April 17, 2009 3:36 AM

I was googling "implement code folding" and run into this post. C'mon guys, code folding is useful. what if your file is 200pg long?! I want to customize code fording for my latex writing---that is, non-programmatic writing. that's how useful it is to me.

Victor on April 23, 2009 1:34 PM

One more vote against regions.

In the real world, most source files are more like 200 lines than 200 pages. When I open a source file, I usually am interested in three things:
1. The class's public interface.
2. The class private members (to see what state it manages)
3. The actual code.

I used to be able to see this at a glance. In my former company, I tried to explain to my colleages that the regions were in the way. One guy responded: "Oh, so your problem is that the editor hides the regions. I hope for you Visual Studio gets better at regions in the future". But as Jeff pointed out: The only reason to put them in is for the editor. Go figure.

anonymous on April 24, 2009 1:57 PM

Have you ever seen a surgeon work? When a surgeon works they cover up a majority of the area and leave what they have just been working on.


To me regions are the same thing. I want to focus on the method or methods I am working on, I don’t need to see the properties or the constructors or the event handlers.

David on May 28, 2009 11:28 AM

It's true: if code requires code folding, that code is evil.

Even though I fully agree with Jeff I realize we're not writing all the code we're navigating through. For example, take all those open-source projects an a significant subset of them that is not exactly a walk in a part when in comes to walking through the code.

With that in mind, when navigating other people's code (e.g. open-source projects) sometimes it's good to be able to fold control structures as well. However, Eclipse (3.2-3.5) does not support it. I've found a plugin for the job:
http://blog.shonzilla.com/post/121086982/extended-code-folding-in-eclipse

Cheers!
Shonzilla

Shonzilla on June 10, 2009 3:20 AM

Those region discussions are really amusing. It's as if there is a law to use or not use them. I myself am using regions in all classes. Even if they are only a couple of lines in them. I group them into a declaration part, constructors, properties, methods, event handling, overridden methods and interface implementations. and maybe some other things if neccessary. And I use sub-regions inside the regions to group things that logically belong together. I think my code is very well structured, and if I find my class does get too long and should be refactored, the regions usually help me because the parts that can be separated usually are in the same region. I do not see an advantage of seeing all the code when I open a file except for that it looks more complex and "impressive". If that's what you need, you really have a problem. If you are too lazy to click once to open a regions...then actually I don't understand why you are not too lazy to use the scroll wheel maybe even a couple of times. (btw. if you're using vs then you should read the manual because you can switch on/off region folding when opening a file in the preferences). I have seen a lot of smelly code by people who tried to avoid regions...well around 50% of code was smelly with or without them, but people claimed it was all fine, in some cases people used hundreds of partial classes which did not make the code any better than with regions, but made it harder to see the code of a single class because you had to browse several files to do so, and in some other cases I got crazy because people insisted on making hundreds of classes to make their code shorter, and seperated things that actually belonged together, with the result that you had to call a.b.c.d.e.f.g to get the value of a property Not to mention how horrible it is to browse to the class that finally contains the property you want (go to definition...go to definition...go to definition...sic!).
Oh, and a big bunch of people are simply too lazy to structure their code and use the smelly code argument as an excuse.
Rubbish, because it's all in your hand if you are ill-using regions to hide bad code. It's like not using cupboards to put your clothes in because some people's cupboards are messy.
But regions help you structuring you code, and group properties and constructures and methods and all together, and easily jump to that region to add a new one. Sure you can do that without regions too...you can also write your code with notepad if you want.
Tools like StyleCop or such that group your code? Hmmm but if you need them then isn't your code smelly too? Because you claim you do need to hide anything. I do not need any tools to find my way around my code because regions do it all for me...

Ringelsocke on June 18, 2009 7:55 AM

Regions aren't evil in an of themselves. In fact, I've been longing for the idea to spread over into the T-SQL world.

The argument often used is that "if your code is long enough that you feel the need to clump together in a region, it probably needs to be 're-factored'"

This certainly doesn't apply to SQL. If you break up a long SQL, for example, one with many nested queries, you could only do so by creating temp tables, which would result in introducing efficiencies.

Having regions in SQL would allow you to view the whole SQL on one screen (or whatever) and allow you to absorb the intent w/o seeing a list of 75 selected fields. I say, put them in a region and a comment with the options to see the details.

What Vis Studio needs is a way to custom-organize subs as the view, using a tree like interface and to save this view. The code itself would not be grouped in regions, the user would just be able to choose how he wanted to see the subs, much like looking at code in the class diagram-it's just a view of the code.


Chadworthington on June 23, 2009 5:43 PM

If you do not want to change the region code on your Mac according to different region DVD, the best choice would be having an external driver. So your copy software must support external driver.
As I know, Mac DVD Copy Pro support external driver.
http://www.imediacreator.com/mac-dvd-copy-pro.html#131

merso on July 29, 2009 5:52 AM
Content (c) 2009 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.