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.

  1. Get a fresh check out of your source code
  2. Change to a directory that you want to fix recursively.
  3. Get a list of all the files that contain regions and store it for later.
    grep --include='*.cs' -lRP '#region|#endregion' * | tee files
  4. Ensure that grep found approximately the expected number of files.
  5. Remove all of lines with regions.
    for $i in `cat files`; do sed -ibak -r '/#region|#endregion/d' $i; done
  6. Ensure your code builds and your unit tests pass.
  7. Remove whitespace from lines which contain only whitespace.
    for i in `cat files`; do sed -i -r 's/^[ \t]+$//' $i; done
  8. Ensure your code builds and your unit tests pass.
  9. Remove consecutive blank lines, leaving a single blank line.
    for i in `cat files` ; do sed -i '$!N; /^\(\)\n\1$/!P; D' $i; done
  10. Ensure your code builds and your unit tests pass.
  11. Commit!

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?