Who likes #regions in Visual Studio? [closed] - visual-studio

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
Personally I can't stand region tags, but clearly they have wide spread appeal for organizing code, so I want to test the temperature of the water for other MS developer's take on this idea.
My personal feeling is that any sort of silly trick to simplify code only acts to encourage terrible coding behavior, like lack of cohesion, unclear intention and poor or incomplete coding standards.
One programmer told me that code regions helped encourage coding standards by making it clear where another programmer should put his or her contributions.
But, to be blunt, this sounds like a load of horse manure to me. If you have a standard, it is the programmer's job to understand what that standard is... you should't need to define it in every single class file.
And, nothing is more annoying than having all of your code collapsed when you open a file. I know that cntrl + M, L will open everything up, but then you have the hideous "hash region definition" open and closing lines to read.
They're just irritating.
My most stead fast coding philosophy is that all programmer should strive to create clear, concise and cohesive code. Region tags just serve to create noise and redundant intentions.
Region tags would be moot in a well thought out and intentioned class.
The only place they seem to make sense to me, is in automatically generated code, because you should never have to read that outside of personal curiosity.

I like regions, and use them all the time. I use them to group members of the same kind inside classes.
You already have the means to collapse methods, classes and namespaces in the editor. Regions give you an option to create another level that lets you arrange the code in a way that corresponds to what you think is important.

StyleCop doesn't like regions:
SA1124: DoNotUseRegions
Cause
The C# code contains a region.
Rule Description
A violation of this rule occurs whenever a region is placed anywhere within the code. In many editors, including Visual Studio, the region will appear collapsed by default, hiding the code within the region. It is generally a bad practice to hide code, as this can lead to bad decisions as the code is maintained over time.
How to Fix Violations
To fix a violation of this rule, remove the region from the code.
There is some discussion about whether or not this is a reasonable rule.
The consensus seems to be that some people like regions and some people don't - it is up to individual teams to decide. The most important thing is to use a consistent style throughout your project.
One place where regions might be acceptable is to group all the methods that implement a particular interface. It is worth noting that Visual Studio automatically adds a region if you use the code generation feature to provide method stubs for implementing an interface.
The only place they seem to make sense to me, is in automatically generated code, because you should never have to read that outside of personal curiosity.
The partial class feature is better for separating automatically generated code from manually generated code within the same class.
When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

I think that #region is perfectly fine. I've never used it myself, but if you have a large or complex class, it can help with finding what you're looking for. Imagine if you're implementing ID3D10Device1- that's over a hundred methods to implement. You want to just throw them all in one place?

I do use regions to organize bigger constructs in a class, ie. a Dependency Property with callback and methods getting called by this, eg. you have a DP that takes an IEnumerable<T>, and you want to use the weak event pattern to respond to INotifyCollectionChanged. This can take some code, and as I won't be touching it after coding it, I put it in a region.
However, if you resort to regions to structure your logic, this is severe code smell and that's what the StyleCop rule in Mark's post is pointing hat.

while I am programming I use regions a lot they help me keeping my code organised and be able to focus only on parts I care. I always add comments on the regions and what are they about .But when I am done I am always removing them. Its a handy tool, that's all.

IHMO, if you have #region section in a class, it means that you have two behaviors in your class and so you should split your class in two objects.

Related

Obsolete or Changed functionality from f# 1.9.6.3 to 1.9.6.16 (the 2010 beta and 2008 compatible release) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Foundations of F# and Expert F# are probably the two most prevalent books used to learn f#.
Both were written at the time of the 1.9.2/1.9.3 releases.
The website for the Expert book has some errata and details some of the changes in the 2008 CTP release which were relatively minor.
However the CTP release for the 2010 beta (and the corresponding 2008 compatible release) 1.9.6.16 changes much more.
Since the MSDN documentation is largely non existent, especially in terms of changes and data is scattered around blogs I am finding it harder and harder to rely on the current books (especially the expert one) since the f# landscape has shifted too much underneath it.
This question seeks to provide a (hopefully) comprehensive list of those areas which have changed and short details/links to further reading on how to deal with this.
As the basis for this I have added some issue which impacted myself.
The previously linked blog post lists many of the changes in terse form and is a good place to start but it doesn't cover everything by any means.
Attempting to keep to a specific aspect per answer would be sensible since this will make reading it easier.
In specific question form:
What changes have occurred to f# from 1.9.6.3 to 1.9.6.16 that render previous examples (especially dead tree documentation not amenable to easy correction) incorrect or deprecated and what remedial actions are possible.
The signature of Array.sort changed; it used to be in-place, whereas now it returns a fresh array and Array.sortInPlace sorts in place. (That's been a minor problem-point for customers; most other library-renames issues deprecation warnings that steer you in the right new direction, but in this case the function still works, but has a new signature, which can make this difficult to diagnose at-a-glance.)
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Collections.Array.html
A number of books were written before FSharp.PowerPack.dll was split out of FSharp.Core.dll, so for many examples you need to ensure you've added a reference to the powerpack to gain access to certain library functions.
See also http://blogs.msdn.com/dsyme/archive/2008/08/29/detailed-release-notes-for-the-f-september-2008-ctp-release.aspx
Events
Expert F# Chapter 8 section: Events and Wiring
IEvent is entirely deprecated. Instead the various functions are defined on Event instead.
There is no longer any need to use create_HandlerEvent to make a completely compatible .Net event (one consumable from, say c# easily) instead you use the CLIEvent attribute.
If you make your event via DelegateEvent<T> then the resulting event is usable without requiring any reference to the FSharp.Core dll.
If you use Event<T> then you must include a reference to the FSharp core to be able to use it.
Naming convention changes
removal of most '_' within function names
removal of deprecated functions
Specific examples and their resolutions
List
reduce_left to reduce
Seq
sort_by to sortBy
group_by to groupBy
init_finite to init
Several functions including cons and generate_using removed
Array
scan1_left to scanReduce
reduce_left to reduce
Multiple types have moved from being part of the dedicated F# runtime (child namespace of Microsoft.FSharp, in assembly FSharp.Core):
bigint now an alias for System.Numerics.BigInteger.
Tuple is now System.Tuple
#light
#light is the default, as a result some examples online will not compile.
This has a relatively minor impact since most examples used #light anyway.
Syntax changes
with member ... and support removed. Use explicit member this.Foo for each
1.9.4 changes
the change to Symmetric Operator Overloading.
subtle changes to the handling of nulls with boxing and option types

Code Length in IDE ( w/o modeling support ) versus Code Efficiecy in Compilation in Delphi

So - highly hypothetical question and more like discussion about your coding style and practice you use daily.
I will take as example: CodeGear RAD Studio 2009 (sorry to all D7 fans, but Unicode rules).
I have capability to expand/collapse functions/procedures/records and few other complex data structures, but what if code is lengthy?
What makes the task and its accomplishment efficient - the time required to add comments (its req actually) and expand/collapse necessary area or use OMT offered possibilities?
To give example input from myself - I have small app, about 1,5k lines and I do not use Modeling. Is it smart enough or do I lose a lot of time if I need to find some simple references or (event) calls?
If I understand your question correctly, it is a bout finding your way into code (yours or someone elses').
I use Model Maker Code Explorer for browsing through source code (and for refactoring existing code, and creating new code). At EUR 99, it is dead cheap for what it does.
It usually gives me a perfect overview of what I need, and has a nice 'search' interface as well.
If I need more complex searches, I usually use the GExperts (grep) search function: it is blazingly fast, and with good naming of your identifiers, it is usually a breeze to find stuff.
If I understand your question correctly, you want to know what is more efficient:
Use comments and expandable sections.
Use moddeling techniques.
I think it depends on personal style. Modeling can be great, but has dangers of spending too much time creating nice pictures.
We have a large app 500k+ lines. We do not use collapsable sections because we keep our file size acceptable and we have a good file organisation structure. We sometimes use modeling if complex parts are added (class diagrams and state diagrams). And we use lots of comment to explain difficult parts.
If you have Delphi 2009 you can use also the Delphi Class Explorer (in the View menu) in order to see your classes. It seems a little bit cryptic but only for the first 5 minutes. After this you will get used with it.
Also you can use CnPack a very impressive package in order to help you manage your project. Basically, in the IDE appears a new menu called 'CnPack' which has a bunch of wizards to help you find the way out in the source. Some examples:
Uses Cleaner
Procedure List (it gives you the incremental search capability for your procedures - very neat)
Bookmark Browser
etc.

Do you have coding standards? If so, how are they enforced? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've worked on a couple of projects where we spent a great deal of time discussing and writing elaborate coding standards covering everything from syntax layout to actual best practices. However, I have also found that these are rarely followed to the full extent. Many developers seem to hesitate to reject a code review based on coding standard violations alone. I.e. violations are committed to the repository on a regular basis.
My questions are: Do you have coding standards? What do they cover? Are they followed by everyone? And what do you do (if anything) to make sure everybody is following the standards?
I'm aware that there is a similar question here, but my concern is not so much how you could do it, but how you are actually going about it and what are the perceived benefits?
I've worked in places with barely-followed coding practices, and others where they're close to being enforced - or at least easily checked.
A few suggestions:
The most important thing is to get buy-in to the idea that consistency trumps your personal preferred style. There should be discussion of the coding standard both before and after it's instituted, but no-one should be allowed to just opt out of it.
Code reviews should be mandatory, with the checkin comment including the username of the reviewer. If you're using a suitably powerful SCM, consider not allowing checkins which don't have a valid reviewer name.
There should be a document which everyone knows about laying out the coding standards. With enough detail, you shouldn't get too much in the way of arguments.
Where possible, automate checking of the conventions (via Lint, CheckStyle, FXCop etc) so it's easy for both the committer and the reviewer to get a quick check of things like ordering import/using directives, whitespace etc.
The benefits are:
Primarily consistency - if you make it so that anyone can feel "at home" in any part of the codebase at any time, it gives you more flexibility.
Spreading best practice - if you ban public fields, mutable structs etc then no-one can accidentally plant a time bomb in your code. (At least, not a time bomb that's covered by the standard. There's no coding standard for perfect code, of course :)
EDIT: I should point out that coding standards are probably most important when working in large companies. I believe they help even in small companies, but there's probably less need of process around the standard at that point. It helps when all the developers know each other personally and are all co-located.
Do you have coding standards?
Yes, differs from project to project.
What does it cover?
Code(class, variable, method, constant), SQL naming and formatting convention
Is it being followed by everyone?
Yes, every new entrant in project could be asked to create a demo project following organization coding convention then it gets reviewed. This exercise makes developer feel at ease before starting real job.
And what do you do (if anything) to make sure everybody is following the standard?
Use StyleCop and FxCop to ensure they are religiously followed. It would show up as warning/error if code fails to comply with organization coding convention.
Visual Studio Team system has nice code anlysis and check-In policies which would prevent developers checking in code that does not comply
Hope, it helps
Thanks,
Maulik Modi
We take use of the Eclipse's save actions and formatters. We do have a suggested standard, but nobody is actually enforcing it, so there are some variations on what is actually formatted, and how.
This is something of a nuisance (for me), as various whitespace variations are committed as updates to the SVN repository...
StyleCop does a good job of enforcing coding layout practices and you can write custom rules for it if something isn't covered in the base rules that is important to you.
I think coding standards are very important. There is nothing more frustrating than trying to find the differences between two revisions of a file only to find that the whole file has been changed by someone who reformatted it all. And I know someone is going to say that that sort of practice should be stamped out, but most IDEs have a 'reformat file' feature (Ctrl-K Ctrl-D in Visual Studio, for example), which makes keeping your code layed out nicely much easier.
I've seen projects fail through lack of coding standards - the curly-brace wars at my last company were contributary to a breakdown in the team.
I've found the best coding standards are not the standards made up by someone in the team. I implemented the standards created by iDesign (click here) in our team, which gets you away from any kind of resentment you might get if you try to implement your own 'standard'.
A quick mention of Code Style Enforcer (click here) which is pretty good for highlighting non-compliance in Visual Studio.
I have a combination of personal and company coding standards that are still evolving to some extent. They cover code structure, testing, and various documents describing various bits of functionality.
As it evolves, it is being adopted and interpreted by the rest of my team. Part of what will happen ultimately is that if there is concensus on some parts then those will hold up while other parts may just remain code that isn't necessarily going to be up to snuff.
I think there may be some respect or professional admiration that act as a way of getting people to follow the coding standards where some parts of it become clear after it is applied, e.g. refactoring a function to be more readable or adding tests to some form, with various "light bulb moments" to borrow a phrase from Oprah.
Another part of the benefit is to see how well do others work, what kinds of tips and techniques do they have and how can one improve over time to be a better developer.
I think the best way to look at coding standards is in terms of what you hope to achieve by applying, and the damage that they can cause if mis-applied. For example, I see the following as quite good;
Document and provide unit tests that illustrate all typical scenarios for usage of a given interface to a given routine or module.
Where possible use the following container classes libraries, etc...
Use asserts to validate incoming parameters and results returned (C & C++)
Minimise scope of all variables
Access object members through methods
Use new and delete over malloc and free
Use the prescribed naming conventions
I don't think that enforcing style beyond this is a great idea, as different programmers are efficient using differing styles. Forcing programmers to change style can be counter productive and lead to lost time and reduced quality. Standards should be kept short and easy to understand.
Oh yes, I'm the coding standard police :) I just wrote a simple script to periodically check and fix the code (my coding standard is simple enough to implement that.) I hope people will get the message after seeing all these "coding convention cleanups" messages :)
We have a kind of 'loose' standard. Maybe because of our inability to have agreement upon some of those 'how many spaces to put there and there', 'where to put my open brace, after the statement or on the next line'.
However, as we have main developers for each of the dedicated modules or components, and some additional developers that may work in those modules, we have the following main rule:
"Uphold the style used by the main developer"
So if he wants to do 3 space-indentation, do it yourself also.
It's not ideal as it might require retune your editor settings, but it keeps the peace :-)
Do you have coding standards?
What does it cover?
Yes, it has naming conventions, mandatory braces after if, while ... , no warning allowed, recommendations for 32/64 bits alignment, no magic number, header guards, variables initialization and formatting rules that favor consistency for legacy code.
Is it being followed by everyone?
And what do you do (if anything) to make sure everybody is following the standard?
Mostly, getting the team agreement and a somewhat lightweight coding standard (less than 20 rules) helped us here.
How it is being enforced ?
Softly, we do not have coding standard cop.
Application of the standard is checked at review time
We have template files that provide the standard boilerplate
I have never seen a project fail because of lack of coding standards (or adherence to them), or even have any effect on productivity. If you are spending any time on enforcing them then you are wasting money. There are so many important things to worry about instead (like code quality).
Create a set of suggested standards for those who prefer to have something to follow, but leave it at that.
JTest by ParaSoft is decent for Java.
Our coding standards are listed in our Programmer's Manual so everyone can easily refer to them. They are effective simply because we have buy in from all team members, because people are not afraid to raise standards and style issues during code reviews, and because they allow a certain level of flexibility. If one programmer creates a new file, and she prefers to place the bracket on the same line as an if statement, that sets the standard for that file. Anyone modifying that file in the future must use the same style to keep things consistent.
I'll admit, when I first read the coding standards, I didn't agree with some of them. For instance, we use a certain style for function declarations that looks like this:
static // Scope
void // Type declaration
func(
char al, //IN: Description of al
intl6u hash_table_size, //IN/OUT: Description of hash_table_size
int8u s) //OUT: Description of s
{
<local declarations>
<statements>
}
I had never seen that before, so it seemed strange and foreign to me at first. My gut reaction was, "Well, that's dumb." Now that I've been here a while, I have adjusted to the style and appreciate how I can quickly comprehend the function declaration because everyone does it this way.

Standards Document

I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.
I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.
I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?
How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.
Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?
What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:
<com|org|...>.<company>.<app>.<layer>.<function>.ClassName
I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.
First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review.
If you're using a language with an existing standard (e.g. Java, C#), it's easiest to use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it.
In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having any standard is the key.
Coming from the automotive industry, here's a few style standards used for concrete reasons:
Always used braces in control structures, and place them on separate lines. This eliminates problems with people adding code and including it or not including it mistakenly inside a control structure.
if(...)
{
}
All switches/selects have a default case. The default case logs an error if it's not a valid path.
For the same reason as above, any if...elseif... control structures MUST end with a default else that also logs an error if it's not a valid path. A single if statement does not require this.
In the occasional case where a loop or control structure is intentionally empty, a semicolon is always placed within to indicate that this is intentional.
while(stillwaiting())
{
;
}
Naming standards have very different styles for typedefs, defined constants, module global variables, etc. Variable names include type. You can look at the name and have a good idea of what module it pertains to, its scope, and type. This makes it easy to detect errors related to types, etc.
There are others, but these are the top off my head.
-Adam
I'm going to second Jason's suggestion.
I just completed a standards document for a team of 10-12 that work mostly in perl. The document says to use "perltidy-like indentation for complex data structures." We also provided everyone with example perltidy settings that would clean up their code to meet this standard. It was very clear and very much industry-standard for the language so we had great buyoff on it by the team.
When setting out to write this document, I asked around for some examples of great code in our repository and googled a bit to find other standards documents that smarter architects than I to construct a template. It was tough being concise and pragmatic without crossing into micro-manager territory but very much worth it; having any standard is indeed key.
Hope it works out!
It obviously varies depending on languages and technologies. By the look of your example name space I am going to guess java, in which case http://java.sun.com/docs/codeconv/ is a really good place to start. You might also want to look at something like maven's standard directory structure which will make all your projects look similar.

How do you feel about code folding? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...)
9 out of 10 times, code folding means that you have failed to use the SoC principle for what its worth.
I more or less feel the same thing about partial classes. If you have a piece of code you think is too big you need to chop it up in manageable (and reusable) parts, not hide or split it up.It will bite you the next time someone needs to change it, and cannot see the logic hidden in a 250 line monster of a method.
Whenever you can, pull some code out of the main class, and into a helper or factory class.
foreach (var item in Items)
{
//.. 100 lines of validation and data logic..
}
is not as readable as
foreach (var item in Items)
{
if (ValidatorClass.Validate(item))
RepositoryClass.Update(item);
}
My $0.02 anyways.
This was talked about on Coding Horror.
My personal belief is that is that they are useful, but like anything in excess can be too much.
I use it to order my code blocks into:
Enumerations
Declarations
Constructors
Methods
Event Handlers
Properties
Sometimes you might find yourself working on a team where #regions are encouraged or required. If you're like me and you can't stand messing around with folded code you can turn off outlining for C#:
Options -> Text Editor -> C# -> Advanced Tab
Uncheck "Enter outlining mode when files open"
I use #Region to hide ugly and useless automatically generated code, which really belongs in the automatically generated part of the partial class. But, when working with old projects or upgraded projects, you don't always have that luxury.
As for other types of folding, I fold Functions all the time. If you name the function well, you will never have to look inside unless you're testing something or (re-)writing it.
While I understand the problem that Jeff, et. al. have with regions, what I don't understand is why hitting CTRL+M,CTRL+L to expand all regions in a file is so difficult to deal with.
I use Textmate (Mac only) which has Code folding and I find it really useful for folding functions, I know what my "getGet" function does, I don't need it taking up 10 lines of oh so valuable screen space.
I never use it to hide a for loop, if statement or similar unless showing the code to someone else where I will hide code they have seen to avoid showing the same code twice.
I prefer partial classes as opposed to regions.
Extensive use of regions by others also give me the impression that someone, somewhere, is violating the Single Responsibility Principle and is trying to do too many things with one object.
#Tom
Partial classes are provided so that you can separate tool auto-generated code from any customisations you may need to make after the code gen has done its bit. This means your code stays intact after you re-run the codegen and doesn't get overwritten. This is a good thing.
I'm not a fan of partial classes - I try to develop my classes such that each class has a very clear, single issue for which it's responsible. To that end, I don't believe that something with a clear responsibility should be split across multiple files. That's why I don't like partial classes.
With that said, I'm on the fence about regions. For the most part, I don't use them; however, I work with code every day that includes regions - some people go really heavy on them (folding up private methods into a region and then each method folded into its own region), and some people go light on them (folding up enums, folding up attributes, etc). My general rule of thumb, as of now, is that I only put code in regions if (a) the data is likely to remain static or will not be touched very often (like enums), or (b) if there are methods that are implemented out of necessity because of subclassing or abstract method implementation, but, again, won't be touched very often.
Regions must never be used inside methods. They may be used to group methods but this must be handled with extreme caution so that the reader of the code does not go insane. There is no point in folding methods by their modifiers. But sometimes folding may increase readability. For e.g. grouping some methods that you use for working around some issues when using an external library and you won't want to visit too often may be helpful. But the coder must always seek for solutions like wrapping the library with appropriate classes in this particular example. When all else fails, use folding for improving readibility.
This is just one of those silly discussions that lead to nowhere. If you like regions, use them. If you don't, configure your editor to turn them off. There, everybody is happy.
I generally find that when dealing with code like Events in C# where there's about 10 lines of code that are actually just part of an event declaration (the EventArgs class the delegate declaration and the event declaration) Putting a region around them and then folding them out of the way makes it a little more readable.
Region folding would be fine if I didn't have to manually maintain region groupings based on features of my code that are intrinsic to the language. For example, the compiler already knows it's a constructor. The IDE's code model already knows it's a constructor. But if I want to see a view of the code where the constructors are grouped together, for some reason I have to restate the fact that these things are constructors, by physically placing them together and then putting a group around them. The same goes for any other way of slicing up a class/struct/interface. What if I change my mind and want to see the public/protected/private stuff separated out into groups first, and then grouped by member kind?
Using regions to mark out public properties (for example) is as bad as entering a redundant comment that adds nothing to what is already discernible from the code itself.
Anyway, to avoid having to use regions for that purpose, I wrote a free, open source Visual Studio 2008 IDE add-in called Ora. It provides a grouped view automatically, making it far less necessary to maintain physical grouping or to use regions. You may find it useful.
I think that it's a useful tool, when used properly. In many cases, I feel that methods and enumerations and other things that are often folded should be little black boxes. Unless you must look at them for some reason, their contents don't matter and should be as hidden as possible. However, I never fold private methods, comments, or inner classes. Methods and enums are really the only things I fold.
My approach is similar to a few others here, using regions to organize code blocks into constructors, properties, events, etc.
There's an excellent set of VS.NET macros by Roland Weigelt available from his blog entry, Better Keyboard Support for #region ... #endregion. I've been using these for years, mapping ctrl+. to collapse the current region and ctrl++ to expand it. Find that it works a lot better that the default VS.NET functionality which folds/unfolds everything.
I personally use #Regions all the time. I find that it helps me to keep things like properties, declarations, etc separated from each other.
This is probably a good answer, too!
Coding Horror
Edit: Dang, Pat beat me to this!
The Coding Horror article actual got me thinking about this as well.
Generally, I large classes I will put a region around the member variables, constants, and properties to reduce the amount of text I have to scroll through and leave everything else outside of a region. On forms I will generally group things into "member variables, constants, and properties", form functions, and event handlers. Once again, this is more so I don't have to scroll through a lot of text when I just want to review some event handlers.
I prefer #regions myself, but an old coworker couldn't stand to have things hidden. I understood his point once I worked on a page with 7 #regions, at least 3 of which had been auto-generated and had the same name, but in general I think they're a useful way of splitting things up and keeping everything less cluttered.
I really don't have a problem with using #region to organize code. Personally, I'll usually setup different regions for things like properties, event handlers, and public/private methods.
Eclipse does some of this in Java (or PHP with plugins) on its own. Allows you to fold functions and such. I tend to like it. If I know what a function does and I am not working on it, I dont need to look at it.
Emacs has a folding minor mode, but I only fire it up occasionally. Mostly when I'm working on some monstrosity inherited from another physicist who evidently had less instruction or took less care about his/her coding practices.
Using regions (or otherwise folding code) should have nothing to do with code smells (or hiding them) or any other idea of hiding code you don't want people to "easily" see.
Regions and code folding is really all about providing a way to easily group sections of code that can be collapsed/folded/hidden to minimize the amount of extraneous "noise" around what you are currently working on. If you set things up correctly (meaning actually name your regions something useful, like the name of the method contained) then you can collapse everything except for the function you are currently editing and still maintain some level of context without having to actually see the other code lines.
There probably should be some best practice type guidelines around these ideas, but I use regions extensively to provide a standard structure to my code files (I group events, class-wide fields, private properties/methods, public properties/methods). Each method or property also has a region, where the region name is the method/property name. If I have a bunch of overloaded methods, the region name is the full signature and then that entire group is wrapped in a region that is just the function name.
I personally hate regions. The only code that should be in regions in my opinion is generated code.
When I open file I always start with Ctrl+M+O. This folds to method level. When you have regions you see nothing but region names.
Before checking in I group methods/fields logically so that it looks ok after Ctrl+M+O.
If you need regions you have to much lines in your class. I also find that this is very common.
region ThisLooksLikeWellOrganizedCodeBecauseIUseRegions
// total garbage, no structure here
endregion
Enumerations
Properties
.ctors
Methods
Event Handlers
That's all I use regions for. I had no idea you could use them inside of methods.
Sounds like a terrible idea :)

Resources