Leftshift’s Weblog

Techniques to improve your code

Consistency Is Key

I’m sure I am not the only one who puzzles over Microsoft’s naming conventions for C#. I understand the Pascal and camel casing rules, but what I don’t get is the exception made for two letter acronyms. I’m looking at creating a dictionary of my code so that I can start to see patterns and opportunities for re-use. To do this I need to be able to break up the name of a method or class into its constituent parts. Regular expressions seemed like a good way to go. It is fairly trivial to write a regex that matches the parts that make up a Pascal and camel cased identifier. What makes this tricky is the exception for short acronyms. Here is my attempt:

Regex splitName = new Regex(@”^I(?=(\p{Lu}{2})*(\p{Lu}\p{Ll}|$))|(^\p{Ll}+|\p{Lu}\p{Ll}+|\p{Lu}{2})”);

It breaks down like so:


Match an I at the start of the name where it is followed by an even number of upper case characters and then either a Pascal name or the end of the string. If this is true we have an interface name such as IEnumerable and we match the first I. BTW the \p{Lu} matches an upper case character and the \p{Ll} matches a lower case character. With interfaces taken care of onto the next part.


So this matches 1 or more lower case characters at the start of a string [camel casing] or an upper followed by one or more lowers, or two uppers.

What this will do is provide a list of the parts that make up a name. What it won’t do is validate the name adheres to the standard.

Some examples:

1.  AnotherReallyLongPascalCasedNameWithDBParametersAndHtmlIO
2.  IInterfaceThatDoesSomethingWithDBAndIO
3.  IODBUIMethodThatDoesSomethingWithIO
4.  anotherReallyLongCamelCasedNameWithDBParametersAndHtmlIO

And the resultant matches

1.  Another Really Long Pascal Cased Name With DB Parameters And Html IO
2.  I Interface That Does Something With DB And IO
3.  IO DB UI Method That Does Something With IO
4.  another Really Long Camel Cased Name With DB Parameters And Html IO

10 June 2008 - Posted by | .NET, Code Quality | ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: