CodeWatch sample fields with underscore convention check

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.

Follow me:

5 thoughts on “CodeWatch sample fields with underscore convention check

  1. Tomasz Pluskiewicz

    It’s weird that you set this up as tests. Why not implement your rules with Roslyn as Analyzers? Not only their easier to consume, you can also implement quick fixes for VS.

    Reply
    1. Pawel Post author

      Is it easy to implement rules with anything. The point is who else will understand them during maintenance.
      Are there any samples of Roslyn Analyzers?

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *