Tuesday, February 03, 2009
Removing C# #regions
I hate C#'s #region directive. Far too many folks abuse it. Even when it's not abused, Visual Studio's default settings (at least once upon a time) didn't allow you to search in a closed region, which drove me crazy. Jeff Atwood had a thorough piece about #region's evils.
A coworker of mine was about to go postal after dealing with some highly #regioned code, so I offered to fix it up for him. There are probably a bajillion ways to remove regions already, but here's another. This assumes you've got a Unix environment at your disposal.
- Get a fresh check out of your source code
- Change to a directory that you want to fix recursively.
- Get a list of all the files that contain regions and store it for later.
grep --include='*.cs' -lRP '#region|#endregion' * | tee files
- Ensure that grep found approximately the expected number of files.
- Remove all of lines with regions.
for $i in `cat files`; do sed -ibak -r '/#region|#endregion/d' $i; done
- Ensure your code builds and your unit tests pass.
- Remove whitespace from lines which contain only whitespace.
for i in `cat files`; do sed -i -r 's/^[ \t]+$//' $i; done
- Ensure your code builds and your unit tests pass.
- Remove consecutive blank lines, leaving a single blank line.
for i in `cat files` ; do sed -i '$!N; /^\(\)\n\1$/!P; D' $i; done
- Ensure your code builds and your unit tests pass.
- Commit!