Jump to content

CodeWatch sample fields with underscore convention check

Posted on:January 26, 2017 at 01:00 AM

This time I’ll talk little bit about code best practices. Usually one thing what every development team does at the beginning of the project is to agree on some conventions. We agree to call services in certain way. Give view models ViewModel suffix and so on. During code reviews we try to catch all those kind of issues… it’s annoying and silly to waste time on somethings like that.

Problem

We tend to forget all those conventions and coding standards during daily programming practices. In SCRUM rush we don’t think, we act. ASAP after ASAP. This is a great time to take technical debt and break agreed coding standards. After a year we end up with something. Which coding standards should a new developer in our team use?

Conventions

Conventions on our context are development team agreements on how we program. What are the rules we follow. For example each interface in C# should start with “I”, custom exception end with “Exception” suffix or private field start with underscore.

There are even also unit tests approaches to ensure conventions. More about that here (Kozmic EN), here (Aniserowicz Video PL) and here (Pawlukiewicz PL).

I think this approach is good. The only thing that bugs me a little is the amount of code. This is what I wanted to hide inside CodeWatch. For me convention tests are coding standards documentation for particular project. They should be easy to read, understood and modify.

Solution

Here is sample how you can create a test for checking that all private fields start with underscore.

namespace Gmtl.CodeWatch.SampleProject.Tests
{
    public class GlobalContextTests
    {
        [Test]
        public void EnsureAllFieldNamesStartWithUnderscore()
        {
            CodeWatcherConfig config = CodeWatcherConfig.Create()
                .WithWatcher(c => new FieldNamingFirstLetterWatcher(c).Configure(Naming.Underscore))
                .WatchAssembly(typeof(DomainModel).Assembly)
                .Build();

            //execute configuration
            var result = config.Execute();

            Assert.False(result.HasIssues);
        }
    }
}

The code above should be fairly easy to understand. And maintain :)

CodeWatch is open source lib available as NuGet package here.