Replacing spaces with underscores makes your head hurt

OK, I’m going to say it, I_like_long_unit_test_names_with_underscores. I’ve been doing this for quite a while now and it hasn’t annoyed me since.  YesYouCanWriteItLikeThis, but it looks different. I don’t know if there are people out there that have trouble focusing their eyes, but they would definitely have problems focusing on these kind of test descriptions.

Something that I have heard from a developer more than once is that this style is not practical. Typing underscores between words makes your head hurt and that is absolutely true.
But! I have a trick for that. A Visual Studio macro!

What reminded me to write a blog post about it,  is Visual Studio 2010. I’m running vs2010 as my main development environment at home now and I’ve noticed that my beloved macro for replacing spaces with underscores is not there. Luckily I still have vs2008 installed on my machine so it’s a matter of copy/pasting. So without further ado, here is the macro… (Oh, and yes macros are in VB and that’s nothing to be ashamed of.)

Sub ReplaceSpacesWithUnderscores()
    Try
        DTE.SuppressUI = True
        DTE.ActiveDocument.Selection.StartOfLine( _
            vsStartOfLineOptions.vsStartOfLineOptionsFirstText, True)
        DTE.ActiveDocument.Selection.WordRight(True, 2)
        DTE.ActiveDocument.Selection.Text = _
            DTE.ActiveDocument.Selection.Text.Replace(" ", "_")
    Finally
        DTE.SuppressUI = False
    End Try
End Sub

The easiest way to get it in VS is to start it first and then press <alt>+<f11> for the Macro Editor. In the editor create a new module for this function and paste this in and close the editor.

Back in Visual Studio goto Tools | Options | Environment | Keyboard or the preferred way<alt>+<t> <o> <k>. In the keyboard options dialog you can search for the new macro by typing in a part of the method name, like WithU. Select the macro and type in a keyboard shortcut. Mine is <ctrl>+<alt>+<shift>+U (for underline). Make sure you click on assign before the OK button. The OK button will not save your binding only the assign button.

With that done, what do you get? Suppose you type the following…

[TestMethod]
public void When something happens Then expect something else

A method name with spaces in it and you reach the end of the sentence, then you activate your shortcut and tada! Underscores

[TestMethod]
public void When_something_happens_Then_expect_something_else

Hope you find this useful and if you also have a favorite macro, let me know!

See you next time.

Advertisements

About this entry