views:

741

answers:

19

I was wondering if there is some standard way to divide a class into regions. almost every project is using a different "region approach" (even classes within the same project).

We pay so much attention to naming conventions and so little to the class's structure. I think that introducing some standard will make it much easier on us to jump into a new code.

I for example use the following :

public class SomeClass
{
     #region Consts
     #endregion

     #region Fields
     #endregion

     #region Properties
     #endregion

     #region Construction
     #endregion

     #region Public Methods
     // Class's API
     #endregion

     #region Overrides
     // Different region for each class override
     #endregion

     #region Private Helpers
     // private methods used only to support external API Methods
     #endregion
}

This is for a basic class of course. when the class is more complicated, more regions are introduced (Destruction, Abstract Methods and so on).

what do you think about that? what regions do you use in your classes?

EDIT

After reading some of the answers I feel that I need to sharpen the question (Alt + Enter if you know what I mean :)):

Do you think that using regions can improve the readability of your code? If so, do you think that introducing some standard way to do it will simplify the way we read other people code?

Another Edit

About the single responsibility issue - I didn't introduce regions like "file handling" or "input handling". the regions I used are ones that will probably be present in any class you'll write. sometime I'll want to see only the API that this class is exposing and some other time I'll want to see only the private methods or the overrides. again, in that case, I don't see any harm by hiding some code.

+2  A: 

Resharper can rearrange your file like that. I can't remember if it will insert region tags as well. I don't really like regions myself, so I haven't looked into it.

Brian Rasmussen
It will, if you tell it to, in the rearrange code options. Don't quite remember where. =)
J. Steen
Thanks for the update.
Brian Rasmussen
Resharper > Options > Languages > C# > Type Members Layout
J. Steen
+33  A: 

I've gone off using regions altogether, find it helps to keep class size tighter as need for so many regions could be a sign that class is getting too large.

dove
Definitely +1, we had a guy at work who like to use regions, so anytime you open one of his classes it's like "oooh, this class only has 60 lines, how neat", when in fact it's just got the other 1800 or so lines of shit code hidden.
Ed Woodcock
+1 Just wanted to add the same thing. Often regions seem to me as a quick way to hide "smelling" code and bad practices like really complicated pieces of classes cry to be refactored.
Juri
+1. I will confess to over zealous use of regions for the first couple of years coding in C#; I still logically group members together, but agree that if you need to collapse code in a class, it may be a sign that it needs refactoring.
Si
+1: I actually *just did this* literally yesterday: I had a whole bunch of ugly code that I initially hid behind #regions... which looked ugly and stupid, so I refactored the code and now it's much nicer.
XXXXX
I have a rule I stick to for regions: only for non-logic code. Field declarations and properties can take up a good amount of useful screen real-estate and I'd rather have the logic code up front and visible. Note that I consider properties with non-trivial bodies as logic code as well.
Ron Warholic
@Sid - That is what I do as well.
Andrew Hare
+2  A: 

I rarely use #region as they don't improve your code. There are plenty of easy ways to navigate your code even without extra Visual Studio add-ins and if you really need to hide some of your code you should perhaps rewrite it?

Martin Liversage
+5  A: 

Just that you're asking -- and asking here -- is good evidence that there is no standard way; standards are, by definition, ubiquitous.

There are of course better and worse ways (and, as dove remarks, no way at all is one of the ways). But you can probably figure that out on your own, or use the preferences of some tool such as Resharper.

Just being internally consistent in a way that seems natural and logical to you is probably good enough.

XXXXX
If you're going to downvote me -- especially for an opinion -- you might at least provide some feedback.
XXXXX
you got my vote
@daemonkid, up or down?
tuinstoel
+1  A: 

I would suggest the following approach:

  1. Divide the class in two main regions, Public members and Private members.

  2. Within each main region, create subregions by logical functionality. For example, Initialization, Invoice management, Customer management (or whatever type of domain-specific services your class offers).

Konamiman
I'm always trying to avoid sub-regions. from my experience it makes the code less readable for me.
Moshe Levi
That's a matter of taste, I guess. In my case, using up to two levels of regionning (as in my answer) helps me to keep the code organized yet readable. But it's true that adding too many levels can be counterproductive.
Konamiman
+17  A: 

Don't use regions: they are counterproductive.

Do regions make your code more readable? No. The fact that code is hidden makes it unreadable!

If you find yourself wanting to hide code, then it is an indication that the class is probably doing too much (and breaking the Single Responsibility Principle).

Refactor into separate classes rather than hiding code.

See Jeff Atwood's post: The Problem With Code Folding

Mitch Wheat
That's just your opinion... I find it very useful to keep the code organized, even for small classes which clearly don't break the SRP
Thomas Levesque
It's not *just* my opinion. It's based on solid logic. The whole reason classes exists is to encapsulate like behaviour.
Mitch Wheat
Code is there to be read and understood by a human. It's supposed to be visible.
Mitch Wheat
I think it's important to note that the solution is not just breaking code into seperate classes (basically doing nothing more than collecting a few methods in a seperate file and tacking a name on it), but redesigning the code so it logically fits into multiple classes. I'm sure that's what you meant, but I felt the need to make it explicit.
Joren
When using VB at work, I always 'hide' the properties within their own regions. For the most part, they are only replications of the actual fields of a class. In the gui class, I also group either all events into a single region, or regions of events into their own region.
Josh Smeaton
@Josh Smeaton: does VB.net have auto properties?
Mitch Wheat
Beware of broad generalizations. Regions can be used for good or bad. If used sparingly, I think they're great. If it's some document-like outlining scheme, I find it annoying.
Jim B-G
@ Jim B-G: I totally disagree. Regions are bad M'ok?....For the reason mentioned above.
Mitch Wheat
@Mitch - nup, no auto properties in VB yet. They're coming in CLR4, or VS2010, or something new and shiny.
Dan F
@Dan F: I'm guessing I should really know that!
Mitch Wheat
+1  A: 

I was once like you; wanting to organise everything into specific regions. I tried it for a while, and got quite bored.

It's better just to write things in a common order; and, as everyone else has said, not have your classes so large that such a scheme is legitimately necessary.

The best thing for readability is consistency; if you lay out your classes in the same way, in the one project, and keep them concise, that's about all you need to do.

It's now really rare for me to use regions, and I have once or twice (I think), but I certainly don't believe a regular class should have a standardised set of regions in it. Note that it's just that I don't "believe" it; if it floats your boat, give it a try, and keep it consistent, and life should be good.

Noon Silk
+1. FWIW although I no longer use regions, if you use Sandcastle to build your docs, I found the order that it produced for members logical.
Si
A: 

Hi, consider using Visual Studio templates for things like class \ interface definitions - we've created them in our company (not difficult to do) and you can do right click->add item-> and VS will create a blank class with the format you've specified. See http://msdn.microsoft.com/en-us/library/ms247121.aspx for more info.

What is the relevance to this question about preprocessor regions?
Joren
probably the fact you could lay out the files once and then reuse that pattern later
Matthew Whited
yes, that's right: DRY...
+1  A: 

Like most of the posters I lean to towards avoiding regions.

However, I do sometimes like to fold the public/ private/ protected/ internal parts away. In this respect it's a shame we departed from the way C++ defines these accessibility modifiers

Think about how you want to read the code. Either you're looking at the public interface, in which case the public region (and probably just the signatures), or you're implementing (or otherwise looking at the implementation), in which case you probably just want to see the whole thing. You may also be implementing a derived class, in which case you want to see the public/ protected parts. You might want to add internal too.

Since, in all cases, you want to see the public section, I don't put this in a region at all.

Other than these views I see little benefit in them.

Phil Nash
+1  A: 

I'm probably going to sound like a broken record because many people in this thread already voiced their opinion against using regions. Concentrate on making your code more readable instead of hiding the code. When I see code that collapsed with regions I always press Ctrl+M+L so I can see everything.

If a class is too big, it's a sign that the code needs to be redesign and probably principle like single responsibility needs to applied.

Vadim
A: 

It very much depends on personal preferences but I'd say

  • regions for logically grouping things like methods etc.. depends on preferences but is not a bad thing
  • regions potentially within methods or for hiding large pieces of code etc..is really bad practice and you should consider refactoring instead.
Juri
+3  A: 

I would have to say, I've never heard anyone say, "I didnt notice the class size was getting large, darn regions!". We're all smart people here and we should be able to determine if we need to take a new approach (or redesign) our work if it starts to smell bad. As for a standard, there isnt one that I know of. It's more of just person preference. I like to define my regions in the following way:

1) Constants
2) Members
3) Constructor/Finalizer
4) Properties (get/set)
5) Helper's

Regions wont improve the readability of your class, especially if its someone else looking at it. More than likely they will have to look at all the code anyway, but it will help organize things to make them easier to find and to keep scrolling to a minimum when working on a select portion of a class. See keystrokes CTRL+M + M, L, O, P, if you want to minimize/maximize regions.

SwDevMan81
A: 

Using regions for seperating logical or syntactical parts of a class
I don't use regions at all anymore. I used to use them because my classes were poorly designed and adding regions seemed a convenient way to keep the logical parts of my class distinct. Now I know better.

On the other hand, using regions just to seperate public from private methods, fields from properties, or similar things is fine by me. I like being able to distinguish these parts of a class on a glance. But instead of regions I prefer just using a blank line or two extra between those areas. That's enough to visually distinguish them, without adding clutter.

Using regions for hiding irrelevant explicit interface implementation details
The only thing I currenly use regions for is for explicit interface implementations. For example, implementing IEnumerable<T> requires implementing non-generic IEnumerable explicitly. As the implementing code only exists because of a framework artifact and not because I want it to be there, and since the explicit implementation only does trivial calls to the normal implementation anyway, I feel fine hiding it away in a region.

Joren
+1  A: 

I can understand that you want to 'sort' your code. First consts, after that readonly static fields, non-readonly static fields, readonly instance fields, non-readonly instance fields, props, constructors, destructors, public methods, private methods, event handlers.

But why adding regions when you have already sorted your code? Focus on keeping your classes small.

tuinstoel
A: 

The only place I've ever used regions without regretting it is in a class I built that wraps a huge COBOL data structure. It contains a private class with a jillion little fixed-length byte[] arrays and accessors that use the AsciiEncoding class to manipulate them. Once I got that private class working, seven years ago, I've never had to look at it once. So it's in a region.

My feeling in general is that once a class gets to be of a certain size and complexity, if it can't be refactored to simplify it, you need to use automation to organize its members. Automation never forgets to member in the right place, nor does it to forget to move a member if you change its name or access.

I also find that once you have good code-navigation features built into your IDE, it doesn't matter how the members of a class are organized. A method's really only relevant in the context of the methods that call it, and a property's only relevant in the context of the methods that use it. There are occasionally exceptions (e.g. if you subclass TextWriter, it's somewhat useful to be able to see that the Write overrides all work the same way, even though they don't call each other), but for the most part, I'm happy just sorting the members of a class by name. This frees me from having to decide "where am I going to put this member?" which, unlike a lot of on-the-fly coding-style decisions, doesn't seem to be one that makes me write better code.

Robert Rossney
how many zeros are in a jilion?
Matthew Whited
+1  A: 

I pattern and organize my regions, if I use them, like the groupings on the help pages of the MSDN library. E.G. Member Variables, Public Properties, Private Properties, Constructors, Destructors, Public Methods, Protected Methods, Private Methods, etc.

Matt Hamsmith
A: 
Loadmaster
A: 

yeah i thought about this too i've came up with my own convention awhile ago, it's pretty much like yours, but an extra root division to static and instance.. i mean, there are two main region, one for static and one for instance, both of them include everything you mentioned (except the const which is a separate oneXD)

Itay
A: 

I admit to being someone that uses regions extensively. I wrap all my methods in their own region but exclude the parameters. (e.g. #region GetStuff as opposed to GetStuff(arg1, arg2...). My reasons are:

  1. When I collapse a property that has its own private field, I want the field to collapse with the property. I want to see one line for the name of the property not potentially three lines for the property, its private field and its collapsed comments. With .NET 3.5 and auto properties, I do not surround them with a region as they are already one line and I can tolerate the extra collapsed line with the comments. I find that putting private variables that only exist because of a property method up at the top to be harder to read and organize.

  2. I want the comments on the property or method to collapse with the method. Way back in the day, I used to always put my comments inside the method specifically for this reason and so that if I copy the routine somewhere else, the comments go with it. MS decided that comments should be outside the method which means that when I collapse the method, I have to separately collapse it comments.

  3. My classes generally do not have more than a dozen or so methods. When I collapse all the methods in the class, I can see the entire class and can quickly find on what I want. I find it far faster than navigating to the drop list or trying use keyboard commands to cycle through or find the method I want.

  4. When I have a method with an overload(s), I put them in the same region. This makes it really nice when they are collapsed as there are fewer lines but they are logically grouped.

  5. Lastly, collapsing the regions makes it easier to filter out the flotsom of other methods and properties and comments that I am not currently concerned with. When you have a class with say a dozen methods that are each say a dozen or two lines, collapsed, there is quite a bit of noise with the different colors, the separately collapsed comments, private member variables etc. Because regions default to grey, having them collapsed is akin to putting them in the background where the code I do care about which is expanded shows quite prominently.

I do avoid regions anywhere other than this purpose.

Thomas