The idea behind the question is - Just say No! to C# Regions
It is said that "the reason to use #region tags because all the things they are hiding is just really bad code."
How do you use regions effectively?
The idea behind the question is - Just say No! to C# Regions
It is said that "the reason to use #region tags because all the things they are hiding is just really bad code."
How do you use regions effectively?
I say "No!" to regions, code folding, and anything else that resembles them. When I'm looking at a source file, I want to see the source. I use search to move around inside the file, so regions can only slow me down.
Absolutely an unresounding yes.
Its a little known fact that regions were actually added to the C# language by Satan himself.
Edit: The only excuse for using them is to hide designer generated code. Using them to group methods/properties by protection level is the most infuriating thing, ever! It achieves absolutely nothing but confusion. If you have THAT MUCH code in a single file, you need to refactor. SRP anyone?
I use #regions to hide designer-generated code, but that's it.
We use a quite strict layout of the class code files (basically nested types such as classes, enums, delegate definitions etc), then static members with fields first, then instance members with fields, then constructors, then the rest). Some tools such as ReSharper support automatic reordering of the members, so that maintaining this structure is not painful at all. But it makes navigation in the file quite intuitive and since then, I haven't used regions anymore.
Regions and code folding can be useful where there are multiple distinct parts to a class, e.g. in a WinForms form separating layout from calling into business logic.
But they are not a substitute for good coding.
I use regions extensively and instantly dislike any code that doesn't structure its various members into logically separated "regions".
Usually, My classes are divided into the following regions:
This is however, a generalization. Some people like to structure class members based on function.
I use regions to hide away large sets of properties and member variables, that's it though
I use regions to group the members of classes, like Properties
, Constructors
and Methods
. It helps keeping a nice structure in the classes, and when compacted you get a nice overview that you can easily navigate without having to use the search (which sometimes takes several seconds just to show up...).
Personally I don't like hammers, because you can break so much with them, including fingers.
I use regions in several cases.
I disagree with the article's author. Using regions does not automatically make you write bad, unstructured code. It really depends of what you are using them for.
For example, I use them to mark different parts of my MVC controller classes, such as Create, Edit and Delete. Edit and Delete contain two different methods (POST and GET) plus a custom View Model in some cases. By wrapping each of these functionalities in one outlining region, I can work on one of them for a longer time without having to see all the other functionalities that do not concern me at the moment anyway.
This does not influence my style of coding. It just makes the file a bit less cluttered with details I do not need to see at the moment. Therefore this usage of code regions is not bad.
If I used code regions to hide a myriad of helper functions and objects which might be better off in their own separate objects, that would be a completely different story. But as I said, I really depends on what you are using code regions for.
I actually like using regions, and feel they can be very useful for making logical groupings in a class. For example I had a class with various derivatives which certain methods corresponded to different things (visual, functional, child object management). Splitting these up into regions makes it clearer where things are, and can give you a good overview if you have appropriately named regions.
You could split these into partial classes, like the designer class is. But ultimately that reaches a very similar conclusion, and you have a lot more class files that you'll need to name appropriately.
You can also use searching, but some of the projects I'm working on, searching is slow. And it's much better if you can learn your way around the code, and find things quickly than having to wait for a time consuming search.
I have also used them within a few algorithms for understanding and maintainability. Honestly I don't think I'd advocate this and it's always better to split things up into methods, but that isn't so easy with the algorithms that I'm working with. Therefore breaking it up into logical sections, and then adding more comments + detail within the regions seemed the best bet to me at the time, and honestly is taking a modular approach to it. You have a method, with a description of what it does. You have regions within the method that explain what that section of code does (with comments) and then you can go down to individual lines of code which may also be commented. So it helps you to drill down to get more information quickly and easily.
I think they're are fine for logical grouping in classes. I think they can work in code/methods but should be avoided if splitting code into more methods is the most suitable approach.
Does it really matter? I am seriously asking this question.
A normal IDE probably has a feature to completely turn off Region hiding. So If someone doesn't like it he can just turn it off. So he will never have something hidden. And if someone like it, then he just use it.
I believe that it is very subjective. A good programmer knows what pieces of code he has to look at no matter if something is hidden with region or not.
I use regions and like them. Amongst other things I find them very handy to wrap up logical groupings of methods in a class. For example I'll have a region for "UI Methods" another region for "Server communications" etc. It makes it very easy to narrow the focus when reviewing a class.
As far as using regions to hide bad code I don't see how anyone could pretend to do that; right click, select Toggle Outlining and all the regions are expanded, not really somewhere safe to hide. If I wanted to hide bad code I'd write a C library and access it with from a .Net assembly with PInvoke, that would keep 95% of .Net developers out.
it's strange, a guy I work with who I would consider our most talented programmer uses regions all over the place. but then he also writes comments like
//create thing
thing someobject = new thing();
With me being the junior and he being the senior engineer, these are things I try to avoid picking up. But like others have mentioned, sometimes it's easy to assume that's the way it's done if you're learning and you see it there already!
1. Perfectly reasonable and downright helpful uses of #regions, for example:
Basically, in practice you may have to include some ugly artifact in your code depending on some tool or some strange requirement which is helpful or needed for some reason, but its not something you want to scroll over all the time. So you compromise by keeping it in your code but stashing it away so its not in your face.
2. Illegal uses of #regions punishable by WTFs such as:
3. Then, there are uses that depend on your preference, such as:
This is a preference, but I believe that it is much more useful to group members by relationship or functionality rather than simply their type.
For example, grouping constructors may make sense because they all perform a similar function and may very well call each other, therefore it may be helpful to group them in a #constructors region. Whereas, you could have several private methods that do all kinds of different functions, some serving one set of properties, some serving the constructors. Therefore, just the fact that they are private methods does not imply that they are strongly related or that they should be grouped. Maybe they could instead be grouped by what kinds of application specific functions they perform. Maybe some are dedicated to order submission and others are dedicated to data conversion.
As developers, we naturally like to group things by type, but we have to remember that it is sometimes more helpful to group things by some functional relation instead.
But, as I said, this last group is largely up to preference, and heavily depends on the type of application and also your mood.
Also, don't forget there are other ways to organize your code such as partial classes or further refactoring of a class into multiple modules.
tl;dr Go ahead, use #regions!
The other day we had a discussion about this at work.
Conclusion: regions represent a code-smell. If your code needs them you should probably refactor.
One of the worst examples I encountered was a method, spanning about 7 screens, which used regions as a twisted form of comments:
#region GetDataForDatabase
.. do stuff..
#endregion
#region FillTheCollection
.. do stuff...
#endregion
So, that's an example of NOT using regions effectively. This post contains a few possible good uses for region. But I'm still not convinced...
I code c# with WPF and found #region quite useful, for example to hide all the dependency property registration and the wrapper CLR properties. Another usage of the #region construct is for example to hide the geometry of an object which extends Shape; once the geometry drawing algorithms is coded, I want to focus on other things and therefore hide it in #region internal geometry.
I simply use it for grouping:
I wonder, how can anybody say that regions are bad ??? I mean, its like saying comments are bad, because regions are just commented containers. Why even arguing about it... don't' use it if you don't like it, don't theory craft about the thing cuz you don't like it.
I see that lot of people here seem to talk about only one category of programs - those that involve large teams, developed for years, with requirements and people changing constantly, in which case you should probably stick with the best practices and patterns. But that's only buisnis programming. There are different kind of people and different kind of programs and not all of them have to look the same !
Now, back to the regions. I use them exclusively. If I have to do 3 tasks in 1 function, I create 3 regions. Refactor? Yeah right... :S How many times will you repeat that. You refactor, I am perfectly happy with my regioned code the way it is.
In order to be good user of regions, you must IMO, implement procedure similar to this one:
Macro to create region of selected code. I keep it on F12
#Region "CreateRegion" :P
Sub CreateRegion()
Dim regionName As String
Dim sb As New StringBuilder
Dim regionBegin, regionEnd As String
Dim selection As TextSelection
regionName = InputBox("Enter region name:", "REQUEST FOR INFO")
'We don't want to go any further if the user clicked cancelled
If regionName.Length = 0 AndAlso WasInputBoxCancelled(regionName) Then Return
selection = DTE.ActiveDocument.Selection
Select Case GetActiveFileExtension()
Case "vb"
regionBegin = String.Format("#Region ""{0}""", regionName)
regionEnd = String.Format("#End Region '{0}", regionName)
Case Else
regionBegin = String.Format("#region {0}", regionName)
regionEnd = String.Format("#endregion {0}", regionName)
End Select
sb.Append(regionBegin)
sb.Append(vbNewLine, 2)
sb.Append(selection.Text)
sb.Append(vbNewLine)
sb.Append(regionEnd)
sb.Append(vbNewLine)
selection.Delete()
selection.Insert(sb.ToString(), vsInsertFlags.vsInsertFlagsContainNewText)
selection.SmartFormat()
End Sub
#End Region 'CreateRegion
I wish there are regions in all editors :D
I say yes... Coupled with Regionerate and my own flavor of regions I love it. I use this on most classes unless they contain such little code that it is unnecessary.
Regions I declare are as follows:
Declarations
Constructors
Overrides
Methods
Properties
Event Handlers
I use #region
only to hide Dispose
logic (for IDisposable implementation)
For all other cases, I try to refactor and keep my class small enough not to use regions.
I both like AND dislike regions.
They are great for organising code into general areas such as 'all properties', 'all fields' etc and then hiding them away - great for stuff like control development were there are usually a lot of properties with backing-store and auto-props can't be used if you're following a notify property change pattern.
And they are great when you are implementing several interfaces and you want to group the interface implementations separately from the main implementation.
But they do get in the way when you want to see the entirety of the code or you are browsing through it looking for something. And even worse when it's someone else's code and they don't agree with your conventions for naming and grouping :-)
What I would like to see is an easily accessible feature in Visual Studio that allowed a 'with-regions' and 'without-regions' toggling option so I could have the best of both worlds when it suited me. Perhaps such things will be easy to implement as extensions to the IDE in VS2010.
The use of regions tends to border on a religious debate, but I tend are with the use of them although I do wish they were more of a comment directive (e.g. /// #region to start a block) as opposed to a preprocessor directive.
In terms of my use of them:
Out side of those areas, I try to avoid regions for the most part and if I see a region inline with some code then it usually raises a red flag in my mind.
I'm by no means a super programmer
but I use regions for 3 reasons
1) seperate methods from form controls ( i no it sounds silly but its a good way for me to no have to scroll through a ton of code to see what i need)
2) to clump code that doesn't appear to belong together but does ( calling a windows dll then the subs related to that
3) the IDE already uses it in various other parts so i figure it can't be that bad.
Personally, I hate regions, and just say NO!
But if I'm working with other developers that use them, I will quell my opinion, as it is just that, an opinion. Being consistent across a codebase is better than forcing my will upon others.
Most of the regions I see separate out different sections, (public methods, public parameters, etc..). I prefer using StyleCop, as this enforces the proper segregation of putting all of your public methods together. I see a region marked as "public methods" as a potential lie, because there's nothing to tell you if public methods exist outside of the region.
On this note, the one thing that I have recently used a region for was to exclude code from StyleCop. Any region with the text "generated code" will be excluded from its criticism. Of course, this should only be used in an extreme circumstance.
I use them to hide huge sets of properties that tend to be in the way while looking through code. I know... OCD... but it drives me nuts otherwise.
The author assumes everyone writes in Visual Studio with ReSharper. Actually, regions are very useful for folding in Vim.
To turn off region collapsing in Visual Studio:
CTRL + M, CTRL + P
Or, from the menu:
Edit > Outlining > Stop Outlining
I use regions for sections of code which I want to collapse, and I want to have other developers not touch.
I put a comment summary in the region line itself, and then a summary at the top of the code block that explains what the block it, why it shouldn't be touched, and why it shouldn't be refactored (why it belongs exactly where it belongs).
Additionally, I haven't printed out a source file in 15 years. It is a general good practice to use regions for organization (in addition to other methods).
I don't use regions, mainly because the #endregion Tag does not have the name. It's nice that you can put "#region name", but it should be mandatory to have "#endregion name" as well, otherwise a compiler error should be thrown (oh, and please none if this "You can just use a comment like #endregion // name", because we all know that this won't work out).
BTW, is there a key combination to jump from a #region to it's #endregion tag and back?
We have regions all around in the software. I absolutely hate them. It's so much noise in the code.
Since it is a German company I suppose they should generally like regions as that nation loves to organize everything even when unasked.
I use them to keep Stylecop happy and to make it easier to find code.
I'm still trying to define a sane style for some things.. for example, should all public classes be in their own file? I dunno. I'm trying all sorts of things to find out what looks the cleanest.
I should also note that I like to group certain things together at times. For example, I may have in my Methods region sections for overrides, utilities, etc. For event handlers I'll try to group like things together such as menu items or things that there may be a lot of similar code you may want to get out of your way. Otherwise, everything is assume alphabetical -- as often as people.
Here is the code snippet I apply to all forms:
#region Constant Fields
#endregion Constant Fields
#region Fields
#endregion Fields
#region Constructors
#endregion Constructors
#region Deconstructors
#endregion Deconstructors
#region Delegates
#endregion Delegates
#region Events
#endregion Events
#region Interfaces
#endregion Interfaces
#region Properties
#endregion Properties
#region Indexers
#endregion Indexers
#region Methods
/*
* Order: (Static comes first, then instance in each section (e.g. public static, public instance, private static, private instance)
* public, internal, protected-internal, protected, private
*/
#endregion Methods
#region Structs
#endregion Structs
#region Classes
#endregion Classes
Regions are actually a form of encapsulation for the programmer, but only at design/coding time, it has no effect at runtime, although it would have been nice to have that.....;)
Given the code base I'm using now, it appears most developers believe a region is a class. Regions often indicate code that is unrelated to the rest of the code in the file, share few dependencies, etc, in otherwords signs that it should be a separate encapsulated class.
Regions encourage bad programming on the level of sabotage.
Regions are the rug under which sloppy developers sweep their shame.
As a maintenance developer, I can't read code with Visual Studio constantly collapsing and hiding code from me.
I remove all regions on sight.
I only use regions for putting a neat header before my properties / constructors / methods etc. Never to hide any actual code. It just irritates me. Better then to use ctrl-M+O to collapse to definitions.
Regions are useful for hiding code that does not need to be edited.
For instance:
Regions shouldn't be used for code that does need to be maintained, because they make it too hard to see the code.
In particular, they don't work properly with outlining. CollapseToDefinitions also collapses the regions. There's no command to collapse method/property bodies but expand regions.
For those of you unfortunate enough to work in a shop that's enamored of regions, here's a macro you can use to collapse methods and properties but expand regions:
Sub CollapseToDefinitionsButExpandAllRegions()
DTE.ExecuteCommand("Edit.CollapsetoDefinitions")
DTE.SuppressUI = True
Dim objSelection As TextSelection =
CType(DTE.ActiveDocument.Selection, TextSelection)
objSelection.StartOfDocument()
Do While objSelection.FindText(
"#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
Loop
objSelection.StartOfDocument()
DTE.SuppressUI = False
End Sub
You can assign that to a key so you can easily collapse but still see the code. The only drawback is that it also expands regions that are inside a method body, which means those methods won't be collapsed. If anyone has any improvements that'll solve that problem, feel free to add them.
My first response to a file containing regions is always CTRL + M + L to expand them all.
At some companies I've worked, they had those visual studio file templates that contained all the regions for the different protection levels and so on. This used to drive me nuts and I had some discussions about me not using them...
Glad to see that many people think like me on the subject. Thanks for sharing the fact that satan himself added the feature, I didn't know that but it does not surprise me!
I use them always but never to hide ugly code. In fact most of the time I use them expanded. Is just a way of enforce code elements organization. I normally have those regions:
Attributes
Constants
Properties
Events
Public Methods
Event Handlers
Private Methods
There are moments while programming that some parts of what you code are "noise" because they are not related whit what you are doing at this moment (for example, attributes when you are defining the public interface, normally properties can be hidden when they have been coded if they are simple getters / setters, etc).
Having less code visible at the screen lets you concentrate in what matters (the code you need).
As TJB said, there are valid uses of Regions.
The best reason IMHO for using regions is for organizational grouping.
For example, I have a SearchDialog where a user can enter field patterns and out pops a search expression used by the parent window. In this code (which gets fairly long) I have a region for "Save/Load Functionality" and another for "Search Expression Generation." With all the members in this class, I've found it especially useful to have all the code related to a specific element of functionality grouped into a single place.
This level of functionality isn't large enough to warrant its own class but yet having it in a single location does make going back in and working with it MUCH easier.
Another helpful use for regions is in interface implementations, particularly when a class inherits from a multitude of interfaces.
Hello guys, I've written a tiny Region Killer tool that handily removes all #region and #endregion from your source code, therefore easing the pain caused by their unholy appearance.
Get it at http://code.google.com/p/rkill/
Have a nice day and remember to eat cookies with milk every afternoon.
Regions hide code -- I want to see the code.
Regions provide text info about the code -- comments do that nicely.
Even turning off the regions leaves a bunch of #region code, cluttering up the code, they are colored blue which makes them look like code rather than comments.
I've just disabled regions for a simple reason, they screw up RockScroll, and that's the one VS add-on I can't live without!
I guess I'm in the minority with my preference on this, but I personally love regions, and have a snippet that I use to add the same structure to every class I write, except the most trivial classes that contain only a few lines of code that fit on one screen. When I try and read someone else's classes that don't use that same consistent approach to filing away the elements that make up the whole object, I find it doesn't make as much sense to me initially, and makes it more difficult, but by no means impossible, for me to grok what my fellow developer was trying to do.
Despite my personal preference, which I recognise is only a personal preference, I don't understand why a tiny minority of people get so hung up over their use by others. I've even encountered such excitable opinions as "they make code un-maintainable" and "they represent bad design"*. [*Both of which comments my last boss put on his public-facing blog, then denied they alluded to my use of regions when I challenged him about his comments (which he hadn't expressed to me personally, and seemed surprised and embarrassed I had read). When I showed him how trivially easy it is to toggle between Collapse/Expand all regions using the Ctrl-M, Ctrl-L and Ctrl-M, Ctrl-O shortcuts in Visual Studio, thereby seeing my classes in the way he preferred, he looked more sheepish still. His lack of courage in criticising my style publicly in a way he thought I wouldn't discover behind my back, and his inability to defend those publicly-expressed criticisms of my coding style when challenged on his views, is a large part of the reason why he is now my ex boss, and left to do it all by himself :) ].
depends how they're used, i just use them to organize large code files, and desginer generated code
Regions help separate large groups of code items (such as functions, fields/properties etc).
If you think they're used to hide "bad code" then you're probably writing bad code yourself.
They're very useful for finding items in large classes.