Extension Method Naming Conventions Best Practices

With .NET Framework 3.5 Extension Methods were introduced to .NET developers. The concept of extension methods allows you to

“[… ] ‘add’ methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.”

While the most common use for extension methods are LINQ standard query operators, extension methods provide aplenty of new possibilities. One issue one comes along is the correct naming if extension methods and their corresponding classes.

The signature of a extension method differs slightly from a common signature as the first parameter is preceded by the this modifier:

public static int WordCount(this string that)

I haven’t found much about naming conventions, most about naming the methods itself, how to organize them or what you should not do with them. If you have read through Robert C. Martin’s Clean Code you might know that naming is an essential foundation of clean code. I’ve read through a lot of code outside and inside of Microsoft, however, I haven’t seen anybody following global guidelines. There might be group specific conventions but nothing that seems to be applied by the majority of developers.

1. Name the type parameter that

This seems to be very odd, but naming the type parameter that has quite some charm. When reading the signature you immediately see the type parameter, when reading through the method body you always know that that is the type parameter the extension is written for. When reading through many extension methods I found it very pleasant to read those methods following this convention.

public static int WordCount(this string that)

2. Create dedicated static classes for each type

No matter whether you put the extension methods in a separate library, in a specific sub-folder within your project or somewhere random

a) Do create separate files for each class containing extension methods.
b) Do create separate classes for each set of extension methods for a certain type.

Once you follow these simple rules you can think straight forward about naming of classes containing extension methods. If you collect all extension methods within a single class (or file) you might end ob with a lot of obsolete code while your application evolves. Due to rewriting your code and refactoring your application same extensions might become obsolete or some classes you extend do not exists anymore in your project. Using dedicated files make maintaining your code base much more easy.

Classes for Extension Methods

3. Use the Extension suffix

During our day job we realized that naming the class with the suffix Extension provide good semantics of the class. This indicates clearly that you are dealing with a collection of extensions. For example, while using the using the Visual Studio Object Browser you can easily identify those classes providing extension methods.

public static class StringExtension
{
    public static int CountWords(this string that)
    {
        ...
    }
}

4. Name what is being extended

It seems to be a good practice to name classes after what they extend. If you follow the previous two guidelines this should be a straight forward job. In addition your code is good to read and easy to understand. In practice we came along various conflicts with already existing naming guidelines. Anyway extensions are a relatively new concepts and one would expect that there might be conflicts with already existing naming conventions. The following will illustrate one of those conflicts:

Naming conventions for Extension Methods

By convention interface names should start with a capitalized ‘I’. So odes ICalculator. Following the above guidelines you might consider naming the corresponding class providing extension methods for the interface ICalculator type CalculatorExtension. In this case it seems reasonable to neglect the convention for interfaces:

Consequently, ICalculatorExtension provides extension methods for the ICalculator type, CalculatorExtension provides extension methods for the type Calculator. This approach will not only increase the maintainability of your codebase, I will also allow new team members to orientate quickly in your codebase.

There are various reasons for and against naming conventions for extension methods. Once writing Reactive Extensions for .NET this might get even more complicated as you will write a lot of extension methods for dedicated purposes. However, for common codebases the provided guidelines might help to develop easy to read and maintain, clean code.

ReSharper 5.0 can Visual Studio 2010 Metadata View

One major drawback of ReSharper 4.5 was the fact if one navigates back to a compiled class, ReSharper always opened the Visual Studio Object Bowser. However, personally I prefer the Metadata View of Visual Studio:
Visual Studio Metadata ViewWith version 5.0, ReSharper (currently available as EAP) comes a major improvement: The first time you navigate to a pre-compiled class, ReSharper offers you to choose your favorite view: Object Browser, Metadata View or directly the .NET framework sources.

JetBrains ReSharper 5.0

In case your change your mind (or the selected sources are not available) you might define the order for the code navigation within Visual Studio at the ReSharper options from ReSharper / Options… / Tools / External sources:

ReSharper Options: External sources

External Applications in MWPSK

My Web Page Starter Kit is a lightweight content management system, entirely written in ASP.NET 2.0. It comes with a wide range of components that can be easily arranged and set up. However, it seems there is no possibility to include external application into the navigation structure of MWPSK.

In the following example you will learn how to integrate a application using the URI http://blog.example.org into a website using MWPSK at http://www.example.org.

Log into the site and navigate to select Administration / Pages and Navigation. Select New Page to create a new

My Web Page Starer Kit - New Page

Choose a virtual path such as blog. This will allow you to use a new URI in the form of http://www.example.org/blog.aspx.

Now open the global.asax file located in the root folder of your MWPSK installation and add the following method.

void Application_BeginRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains
         ("www.example.org/blog.aspx"))
    {
        HttpContext.Current.Response.Status = "301 Moved Permanently";
        HttpContext.Current.Response.AddHeader("Location",
            Request.Url.ToString().ToLower().Replace(
                "www.example.org/blog.aspx",
                "blog.example.org/"));
    }
}

This will cause an URL rewrite of the HTTP-request, which is then sent to the external application at http://blog.example.org.

NETCFv35.Messages.EN.wm.cab!?

Today, I run into a quite annoying error message while developing a application for Windows Mobile 6.1.

“An error message is available for this exception but cannot be displayed because these messages are optional and are not currently installed on this device. Please install ‘NETCFv35.Messages.EN.wm.cab’ for Windows Mobile 5.0 and above or  ‘NETCFv35.Messages.EN.cab’ for other platforms. Restart the application to see the message.”

The required files are located at C:Program Files (x86)Microsoft.NETSDKCompactFrameworkv3.5 WindowsCEDiagnostics, assuming you have installed the Windows Mobile SDK. I copied the file NETCFv35.Messages.EN.wm.cab to my device and run the installation. So far it worked fine, until the same exception popped up again.

Using the .NET CF Logger, from Power Toys for .NET Compact Framework 3.5, I was able to track it down to the following error:

“Failed to load [System.SR, Version=3.5.0.0, Culture=neutral, PublicKeyToken=969DB8053D3322AC]”

To do so, you choose the device you want to log and select which logging options you want. The log files can be found then in your application folder on the mobile device.

.NET CF Logging Options

With this new input, I found Martijn Hoogendoorn’s blog entry. He came across the same issue some time ago and provided a solution to this miracle. If you have a look inside the .cab file, check the _setup.xml file.

 NETCFv35.Messages.EN.wm.cab _setup.xml

Extract and rename the file SYCCFA~1.001 to System.SR.dll and include it into your project. Rebuild, deploy and debug it – it should work fine.

What Is IronRuby?

If you are interested, go to Manning Publications Co. and get an (almost) free White (green) paper about IronRuby. It will cost you only your e-Mail address and clicking the opt-out link as soon as you received the first newsletter.

“IronRuby is an implementation of the Ruby language on the .NET Framework. That means when it’s complete it will have the same language features as Matz’s Ruby Implementation (MRI) 1.8.6 but backed up by the intrinsic power that the .NET Framework harnesses.”

What is IronRuby - Green Paper

How To Order Unit Tests in Visual Studio 2008

Sometimes it is maybe necessary to bring some order into your unit tests in Visual Studio. Indeed, this is not really the idea of unit testing, however it might be necessary for a variety of reasons. Facing this issue, I had to search the MSDN documentation for a while.

I was desperately looking for some syntax like:

[TestMethod(Order = 1)]

However, the only way to bring some order in your tests is, by creating some ordered tests in addition to your unit tests.

To do so, you first create a set of unit tests. In my case, some of the tests should be only executed after other run successfully. Otherwise the result might look like:

Failed Unit Test

Now we create a new test project called Order Test:

Add New Ordered Test

When opening the project you actually can arrange the order of the previously written unit tests:

Arrange an Ordered Test

Running the test then is possible by selecting the test from the Test View window. Your tests will actually only appear as one entry in the list but you will see that all the selected tests run successfully – in the correct order.

Succesfull Ordered Test