views:

49

answers:

1

I've heard bad things about overusing regions but when adding enums to my classes I put them into a #region "Enums" at the end of the class, and do the same with structures and even subclasses.

Is there a better/standard way to go about grouping such elements on classes?

(Note: this is tagged C#/VB but maybe the same situation exists for other languages, like Java)

+2  A: 

Surely a reasonable grouping is to use separate source files.

For classes that are more than a few screens full, you should probably have a separate source file for such a class. Otherwise finding the various classes and other items within a source file can be difficult.

For a collection of enums which are semantically related and which are each small enough to fit on a screen, it often makes sense to put them into a single file — but then you should name the file according to a purpose that all of those enums share. If you have trouble coming up with a poignant name that describes their commonality, then this may be an indication that you should split them up again. (Of course this paragraph applies equally to classes and structs, but only very small ones.)

Notice that even nested classes/structs/enums can be placed in a separate source file in C# — just declare the outer class as partial.

If you have a whole class hierarchy of related derived classes (subclasses), you could even create a subdirectory for each such hierarchy. For example, in a subdirectory called Collections, you might have a file called CollectionBase.cs for the abstract base class and a separate source file for each derived class.

Timwi
I use a separate source file for every class directly below a namespace even if it's small, and my subclasses tend to be small, purpose-specific objects. And most of my enums have only relationship with one class or method of one class. Partial classes are also an option in VB, and this seems a valid point. I thought partial classes were only meant for WPF, +1.
Camilo Martin
What partial classes were originally invented for is irrelevant. It is a general-purpose feature that you can use wherever it makes sense. The same is true of extension methods and lambda expressions — it doesn’t matter that they were invented for LINQ.
Timwi
I just wonder how different it is to split a class into files instead of regions. The arguments against regions have about the same impact with files.
Camilo Martin
Can you link us to a blog post or discussion about the supposed downsides of regions? I haven’t heard of them and I would like to read about them.
Timwi
This is one: http://www.codinghorror.com/blog/2008/07/the-problem-with-code-folding.html
Camilo Martin