My Naming Conventions For Localized Concepts In C#

I’m Portuguese and most of the software I design and develop is about concepts in Portuguese. How should I name stuff?

If I’m talking about Conta or Cliente it’s easy: Account and Customer. And what about concepts that aren’t in English or for which a translation would be unrecognizable?

When I name stuff I try to make things easily recognizable for those who read it, and this brings us to a combination of both Portuguese and English.

When someone finds in the code or documentation ContaInválidaException (names are in Unicode, it’s time to let go archaic prejudice – “conta invalida” means that the account is making something invalida and “conta inválida” means that the account is invalid) identifies immediately what it is. For a business person it’s obvious that it’s something about an invalid account and for a technology person it’s obvious that it’s some kind of exception.

My C# Naming Conventions For Partial Class Files

Following up on a previous post, this time I’ll give you my naming conventions for partial class files.

There are two main reasons for me to break a class definition into more than one file. The main one is when I have inner classes and the other is when the file is getting too big.

How should I name the files? The usual tendency is to use a “.” as separator. This looks nice until you came across something like this:

public class MyComponent

{

    private class Activation

    {

        // Class implementation.

    }

 

    private class Deployment

    {

        // Class implementation.

    }

 

    #region Event Handling

 

    // Event handling code.

 

    #endregion

}

If I would extract the inner classes and use the “.” as separator, I would end up with the following list of files:

  • MyComponent.Activation.cs
  • MyComponent.cs
  • MyComponent.Deployment.cs

And, what about the long event handling code? Should I do the same? If so, I will end up with the following list of files:

  • MyComponent.Activation.cs
  • MyComponent.cs
  • MyComponent.Deployment.cs
  • MyComponent.EventHandling.cs

This doesn’t look very nice, does it?

So, here is my proposal:

  • “-“ separator for code from the top class
  • “+” separator for inner classes

This way, I end up with the following list of files:

  • MyComponent.cs
  • MyComponent-EventHandling.cs
  • MyComponent+Activation.cs
  • MyComponent+Deployment.cs

And this looks a lot nicer.

Enterprise Library 3.1 Released

You can download here.

Before you get too excited, according to Tom Hollander, this is really just a maintenance release addressing a small number of issues discovered since the release of 3.0. Here is a summary of the main changes:

Policy Injection Application Block
  • The default Remoting Policy Injector can now be replaced with alternative interception mechanisms via configuration without modifying the application block code
  • Call Handler attributes are now honored correctly when placed on interface methods
  • Fixed an issue that could cause duplicate handlers where matching rules matched both a class and its interface
  • Classes implementing COM interfaces (including those deriving from System.Windows.Forms.Form) can now be intercepted
  • TraceLogEntry class is now serializable, allowing it to be used with the MSMQ Trace Listener
Validation Application Block
  • Fixed an issue that prevented the PropertyComparisonValidator from working with the Windows Forms integration adapter
  • The message template for the PropertyComparisonValidator can now be saved using the configuration tools.
Data Access Application Block
  • Connection strings for OLEDB and ODBC connections can now be edited using custom dialog boxes from the configuration tools

Naming Conventions for C#

I’m a firm supporter of coding conventions (at least of my coding conventions).

Software factories [^] [^] [^] and other code generation tools have been taking care of writing the tedious (and, sometimes, ugly) code but, at some point, some code must be written and read by human developers. That’s why (in my opinion) the way the code is written is as much important as the language it is written in.

There are several resources about coding conventions for the .NET framework:

I haven’t read Brad and Krzysztof‘s book (yet), but I’ve read MSDN Library‘s guidelines and Juval‘s document and watched Krzysztof‘s presentation.

I have to disagree with Microsoft’s position about naming conventions of private members. In an enterprise as big as Microsoft projects start and end, people move between teams and every time someone changes team he/she is faced with the possibility of having to learn and adapt to a new set of naming conventions for private members.

IDesign goes one step further on defining naming conventions for private members. I just don’t like the convention they used. What’s the point of prefixing private member fields (not variables as in their document) with m_? What does it mean? Member? If it’s not a local method variable or a method parameter it’s a member.

Some just prefix with _. Once again, why? What does that mean?

The only reason I can find for this prefixing practice is lost in the old days of colorless IDEs, printers and books. With colorful IDEs like Visual Studio 2005 you just need to qualify instance member fields with the this (Me for Visual Basic) keyword and static (Shared in Visual Basic) member fields with (lacking of a better solution) the class name.

Lets pretend for a moment that I’m one of the prefixes. How would I do it?

  • i_camelCase for private instance members.
  • s_camelCase for private static members.
  • c_camelCase for private constants.

Why stop there? Let’s also prefix method variables:

  • v_camelCase for method variables.

Now I’m on a roll. Let’s prefix method parameters:

  • i_camelCase for input parameters.
  • o_camelCase for output parameters.
  • r_camelCase for by reference parameters.

The next step would be to go Hungarian and add type information to the names, right? No. Let’s stop here and get in the right track.

My Naming Conventions for C#

I Find that keeping naming conventions as simple as possible is the best way use and validate them.

  1. Pascal casing for any class/struct member (constants, fields, properties, methods, events) except for private fields.
  2. Camel casing for private fields and method/property parameters and variables.
  3. Prefix interface names with I (IAccountService).
  4. Prefix type parameter names with T (TKey, TValue).
  5. Suffix type with meaningful names for its purpose (AccountService, InvalidAccountException, MustVerifyAccountAttribute, FromAccountTextBox).
  6. Method names must reflect what they are supposed to do. Methods always do something, so they must start with a verb. (GetAccountInformation, UploadFile)
  7. Names must be descriptive. Abbreviations should not be used. Hungarian notation should not be used. Single name variables should not be used.
  8. Language keywords should be used instead of type names (string instead of System.String, int instead of System.Int32, etc.).
  9. Business relatad names should reflect business entities or actions, and in the business’ language (GetContaFromDataBase, ContaInválidaException, ValidarContaAttribute).
  10. Underscores should not be used. Camel casing should be used to separate words.
  11. Acronyms should be treated as a single word. Just to be compliant with Microsoft, for acronyms with less than three letters, all letters should be upper case.

TypeMocks™ 4.0.0 is now available

TypeMocks™ 4.0.0 is now available.

In my previous analysis mentioned two drwanbacks of this mocking framework:

  1. The lack of a mocking scope.
  2. The lack of the use of Generics in its APIs.

Let’s start with the second one.

Generic Reflective API

TypeMocks™ was the same tool for both the .NET 1.1 and the .NET 2.0 runtimes and they were avoiding the need to have two tools. But we already need two runtimes and two IDEs, so two versions of TypeMocks™ isn’t such an hassle. I’m glad they came to their senses about this.

Befere this new API, the usage of mocks was something like this:

MockObject mockObject = MockManager.MockObject(typeof(IIdentity));

mockObject.ExpectGetAlways(“Name”, “username”);

IIdentity identity = (IIdentity)(mockObject.Object);

Now, it’s more like this:

MockObject<IIdentity> mockObject = MockManager.MockObject<IIdentity>();

mockObject.ExpectGetAlways(“Name”, “username”);

IIdentity identity = mockObject.Object;

You’ll have to agree with me that the changes in lines 1 and 3 improve the reliability and readability of the test code.

Mocking Scope

The need for this one may not be obvious, so let’s look at an example.

Imagine we are testing this class:

public class TestedClass

{

    string value;

 

    public TestedClass(bool create)

    {

        if (create)

        {

            this.value = new ClassUsedByTestedClass().Value;

        }

    }

 

    public string Value

    {

        get

        {

            return this.value;

        }

    }

}

As you can see, TestedClass uses ClassUsedByTestedClass:

public class ClassUsedByTestedClass

{

    public ClassUsedByTestedClass()

    {

        throw new NotImplementedException();

    }

 

    public string Value

    {

        get

        {

            throw new NotImplementedException();

        }

    }

}

Now, take these two tests:

[TestMethod()]

public void TestMethod1()

{

    const string mockedValue = “mocked value”;

    const bool create = false;

 

    using (RecordExpectations recorder = RecorderManager.StartRecording())

    {

        ClassUsedByTestedClass c = new ClassUsedByTestedClass();

        string v = c.Value;

        recorder.Return(mockedValue);

    }

 

    TestedClass t = new TestedClass(create);

 

    Assert.AreEqual(mockedValue, t.Value);

}

 

[TestMethod()]

[ExpectedException(typeof(NotImplementedException))]

public void TestMethod2()

{

    const bool create = true;

 

    TestedClass t = new TestedClass(create);

}

These two tests will fail because the value of create in test one is wrong. To shield ourselves from this kind of mistakes, we can code the tests this way:

[TestMethod()]

public void TestMethod1()

{

    MockManager.ClearAll();

 

    const string mockedValue = “mocked value”;

    const bool create = false;

 

    using (RecordExpectations recorder = RecorderManager.StartRecording())

    {

        ClassUsedByTestedClass c = new ClassUsedByTestedClass();

        string v = c.Value;

        recorder.Return(mockedValue);

    }

 

    TestedClass t = new TestedClass(create);

 

    Assert.AreEqual(mockedValue, t.Value);

 

    MockManager.Verify();

}

 

[TestMethod()]

[ExpectedException(typeof(NotImplementedException))]

public void TestMethod2()

{

    MockManager.ClearAll();

 

    const bool create = true;

 

    TestedClass t = new TestedClass(create);

 

    MockManager.Verify();

}

Now it’s clear that the wrong test is the first one. But I like to scope things using the using statement, so, this is a better looking solution.

[TestMethod()]

public void TestMethod1()

{

    using (new MockScope())

    {

        const string mockedValue = “mocked value”;

        const bool create = false;

 

        using (RecordExpectations recorder = RecorderManager.StartRecording())

        {

            ClassUsedByTestedClass c = new ClassUsedByTestedClass();

            string v = c.Value;

            recorder.Return(mockedValue);

        }

 

        TestedClass t = new TestedClass(create);

 

        Assert.AreEqual(mockedValue, t.Value);

    }

}

 

[TestMethod()]

[ExpectedException(typeof(NotImplementedException))]

public void TestMethod2()

{

    using (new MockScope())

    {

        const bool create = true;

 

        TestedClass t = new TestedClass(create);

    }

}

I would be very happy with this last solution. But both these two solutions have have too much mocking infrastruture coded in the test code and, because the people at TypeMocks™ aren’t in the market of just making me happy, they came up with a better solution (available on Professional and Enterprise Editions only):

[TestMethod()]

[VerifyMocks]

public void TestMethod1()

{

    const string mockedValue = “mocked value”;

    const bool create = false;

 

    using (RecordExpectations recorder = RecorderManager.StartRecording())

    {

        ClassUsedByTestedClass c = new ClassUsedByTestedClass();

        string v = c.Value;

        recorder.Return(mockedValue);

    }

 

    TestedClass t = new TestedClass(create);

 

    Assert.AreEqual(mockedValue, t.Value);

}

 

[TestMethod()]

[ExpectedException(typeof(NotImplementedException))]

[VerifyMocks]

public void TestMethod2()

{

    const bool create = true;

 

    TestedClass t = new TestedClass(create);

}

And do you know what they called this? Best Practices Patterns.

Generic Test Decorator

TypeMocks™ is more than just a mocking framework, and it now enables writing custom test decorators. These are test framework agnostic and it is simple to add more features to your tests. Now you can write your own version of VerifyMocksAttribute and ClearMocksAttribute (available on Enterprise Edidion only).

Mock Signed Internal Interfaces

It’s now possible to mock internal interfaces in signed assemblies.

Enhancements to Natural TypeMocks™

It is now possible to create return values within the recording block, saving even more time and having an easier flow.

Before you had to do this:

DateTime d = new DateTime(2007, 5, 20);

using (RecordExpectations recorder = RecorderManager.StartRecording())

{

    TestedClass mc = new TestedClass(new DateTime());

    DateTime v = mc.Value;

    recorder.Return(d);

}

Now you can just do this:

using (RecordExpectations recorder = RecorderManager.StartRecording())

{

    TestedClass mc = new TestedClass(new DateTime());

    DateTime v = mc.Value;

    recorder.Return(new DateTime(2007, 5, 20));

}

There’s also a ReturnDefaultImplementation method in the RecordExpectations class that returns a mock that has default behavior.

.. and several other enhancements and bug fixes.