SOLID: Single Responsibility Principle

swiss-army-knifeA blog about software craftsmanship cannot be complete without mentioning the SOLID principles. I discovered these principles about a year ago and it completely changed the way I write software and think about it. By using SOLID I feel like my code is more robust than before, more understandable, more maintainable and easier to test. Will them solve all your problems? Of course not but, in my opinion, it can definitely help you writing better crafted software. There are 5 object-oriented programming principles in SOLID:

  • Single Responsibility Principle (SRP)
  • Open Close Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

And today I will present the first one, the Single Responsibility Principle, by giving an example and explaining my understanding of this principle.

A class should have only one reason to change.

This is the rule of this first principle. Is that all? Yes it is, so now I will give details about the meaning of this rule and what it implies. If a class has more than one reason to change it means that this class certainly have more than one responsibility. If you are not able to describe the goal of your class with a short sentence you are most likely violating the SRP. And if your short sentence contains words like “or”, “and” or “then” you probably violates this principle as well.

I will use a basic example to demonstrate the concept of this principle. I created the following helper class:

class EmailHelper
{
    public void Validate(string email)
    {
        // some validation logic
    }
 
    public void Send(string email, string message)
    {
        // some sending logic
    }
}

So, what does this class do? I can answer by the following sentence: “This class helps manipulating email addresses”. I did use a short sentence to describe my class and without saying “and” or “or”. True, but in my opinion this is definitely imprecise and it reveals that the SRP might be violated. To describe this class I would much likely say: “This class validates email addresses and sends a message to a given address”. This is much more accurate and it shows that the class has more than one responsibility.

To respect the Single Responsibility Principle, I will create two different classes having each its own responsibility:

class EmailValidator
{
    public void Validate(string email)
    {
        // some validation logic
    }
}
 
class EmailSender
{
    public void Send(string email, string message)
    {
        // some sending logic
    }
}

I now have a class that validates a given email address and another that sends a message to an email address. I can now use the validation logic without having the sending logic in the same “area”. I know that my example might look mundane and sometimes it is much more difficult to tell if the SRP is violated or not. I can only advise you to keep the rule in mind to tell if you are respecting the SRP.

I hope you like this introduction to the Single Responsibility Principle from SOLID. And as always do not hesitate to share your opinion on this topic.

If you want to know more about the SRP and the SOLID principles I recommend to acquire the “Agile Principles, Patterns and Practices in C#” book by Robert “Uncle Bob” Martin and Micah Martin.

See you next time!

The Null Object Pattern

empty-frameIn a lot of object-oriented programming languages there is a moment where we have to deal with null pointers/references/objects. These references must be checked to avoid any exception that might end the program in an unexpected way or moment. I think that most of us have encountered this type of error at least once in our lives. Tony Hoare said that the introduction of the null reference is its “billion-dollar mistake”. Yet sometimes it is possible to avoid the use of null pointer in our application by using the Null Object Pattern.

The intent of this pattern is to provide a specific implementation of an abstraction by doing nothing, it is used to replace manipulation of undefined references (null) when it can be and is therefore predictable (again, it does nothing).

I have created the following piece of code, in C#, to show how it can be done.

public class User
{
    public enum NotificationTypes
    {
        Email,
        Text,
        Twitter,
        None
    }
 
    public string Name { get; set; }
 
    public NotificationTypes NotificationPreference { get; set; }
}
public interface INotifier
{
    void Notify(User user, string message);
}
 
public class EmailNotifier : INotifier
{
    public void Notify(User user, string message)
    {
        Console.WriteLine("Hello {0}, {1} - sent by email", user.Name, message);
    }
}
 
public class TextNotifier : INotifier
{
    public void Notify(User user, string message)
    {
        Console.WriteLine("Hello {0}, {1} - sent by text", user.Name, message);
    }
}
 
public class TwitterNotifier : INotifier
{
    public void Notify(User user, string message)
    {
        Console.WriteLine("Hello {0}, {1} - sent by twitter", user.Name, message);
    }
}
 
public static class NotifierFactory
{
    public static INotifier CreateNotifier(User user)
    {
        switch (user.NotificationPreference)
        {
            case User.NotificationTypes.Email:
                return new EmailNotifier();
            case User.NotificationTypes.Text:
                return new TextNotifier();
            case User.NotificationTypes.Twitter:
                return new TwitterNotifier();
        }
        return null;
    }
}
static void Main(string[] args)
{
    var bob = new User { Name = "Bob", NotificationPreference = User.NotificationTypes.Email };
    var john = new User { Name = "John", NotificationPreference = User.NotificationTypes.Text };
    var martin = new User { Name = "Martin", NotificationPreference = User.NotificationTypes.Twitter };
    var jeff = new User { Name = "Jeff", NotificationPreference = User.NotificationTypes.None };
 
    var users = new List<User> { bob, john, martin, jeff };
 
    foreach (var user in users)
    {
        var notifier = NotifierFactory.CreateNotifier(user);
        if (notifier != null)
        {
            notifier.Notify(user, "This is a message");
        }
    }
}

In this example, a message is sent to several users using the notification system they prefer. And they can turn off the notification system by choosing the “None” option and in this case the Notifier instance returned by the factory is null and force us to put a check in the calling code to avoid any NullReferenceException. As you can see, if the Notifier is null there is no particular behavior, this is a sign that the Null Object Pattern might be used. To use this pattern, the first thing to do is to add a new implementation of INotifier:

public class NullNotifier : INotifier
{
    public void Notify(User user, string message)
    {
        // Nothing to do
    }
}

I can now update my factory to return an instance of this new class instead of null:

public static class NotifierFactory
{
    private static INotifier NullNotifier = new NullNotifier();
 
    public static INotifier CreateNotifier(User user)
    {
        switch (user.NotificationPreference)
        {
            case User.NotificationTypes.Email:
                return new EmailNotifier();
            case User.NotificationTypes.Text:
                return new TextNotifier();
            case User.NotificationTypes.Twitter:
                return new TwitterNotifier();
        }
        return NotifierFactory.NullNotifier;
    }
}

Since the Null Object Pattern is stateless, it is common to use it as a Singleton, this is why I used a static field to hold the reference to the pattern. I can now clean the caller code by removing the null check:

static void Main(string[] args)
{
    var bob = new User { Name = "Bob", NotificationPreference = User.NotificationTypes.Email };
    var john = new User { Name = "John", NotificationPreference = User.NotificationTypes.Text };
    var martin = new User { Name = "Martin", NotificationPreference = User.NotificationTypes.Twitter };
    var jeff = new User { Name = "Jeff", NotificationPreference = User.NotificationTypes.None };
 
    var users = new List<User> { bob, john, martin, jeff };
 
    foreach (var user in users)
    {
        var notifier = NotifierFactory.CreateNotifier(user);
        notifier.Notify(user, "This is a message");
    }
}

Now my application has the same behavior as before and is cleaner. With the Null Object Pattern I have been able to remove a check for a null reference in my code without losing any functionality. This pattern may look like a test double but its purpose is not for testing, it’s for production code and match a case of the domain model: in my example the absence of notification is a deliberated choice.

The Null Object Pattern is often used with the Factory pattern (like in my example). You should consider this pattern if you have null check over an abstraction that does not trigger any behavior.

I hope you like this presentation of the Null Object Pattern, and as always do not hesitate to comment.

See you next time!

Model validation in ASP .NET MVC

form-validation

I worked for several years as an ASP .NET MVC developer and I still do even if I do less front-end development at the moment. During my professional life I came across a few tips for this technology that helped me making my code cleaner and less coupled.

Before creating this blog I owned another one in french where I posted a few articles related to Model validation for a form. I will expose the concept of these articles in this new blog post, in english this time. Maybe it will look obvious for you but I wish I knew these tips when I started working with ASP .NET MVC and this is why I’m creating this blog entry, it might help some of you.

The problem

I created the following form for example, which ask for a name and an IP address:

I created this form using a new empty MVC application in Visual Studio and here is the Index.cshtml view:

@model CodingTips.Web.Models.IPAddressModel
 
<h2>IP Address form</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div>
        @Html.LabelFor(m => Model.Name):
    </div>
    <div>
        @Html.TextBoxFor(m => Model.Name)
        @Html.ValidationMessageFor(m => Model.Name)
    </div>
    <div>
        @Html.LabelFor(m => Model.IPAddress):
    </div>
    <div>
        @Html.TextBoxFor(m => Model.IPAddress)
        @Html.ValidationMessageFor(m => Model.IPAddress)
    </div>
    <input type="submit" />
}

The Model and the Controller are defined the following way at the moment:

public class IPAddressModel
{
    [Required]
    [Display(Name = "Your name")]
    public string Name { get; set; }
 
    [Required]
    [Display(Name = "Your IP address")]
    public string IPAddress { get; set; }
}
 
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(IPAddressModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
 
        return RedirectToAction("Validate");
    }
 
    [HttpGet]
    public string Validate()
    {
        return "Your IP address has been registered";
    }
}

As you can see I already put some validation logic that will only verify that the fields are not left empty. If the user fill the two text boxes he will be redirected to a page containing only a confirmation message, this is the final result.

But, as you probably guessed it, there are issues with this validation code, the IP address field can be filled with any string value and the Model will be valid. This is not what we desire, we want a more accurate validation for this field and this is what I will show in this article.

When I began working with ASP .NET MVC my first thought, when I encountered an issue like this one, was to add all the validation logic inside the POST action of the Controller. Well, it can work but this is not the place to do so, this option increase the code coupling especially when the Model to validate is huge. In my opinion the Controller should only take care of the “flow” logic of the application and the validation should be placed somewhere else.

The good news is that ASP .NET MVC has been designed to be extensible for Model validation in an easy way. Let’s see how this can be done.

IValidatableObject

It is possible to add validation at the class-level, directly on the Model itself by implementing a specific interface: IValidatableObject. There is only one method available in this interface, the Validate() method. It will be automatically called by the MVC framework when the ModelState.IsValid code is executed, which is already present in our Controller. Let’s see the new version of the Model:

public class IPAddressModel : IValidatableObject
{
    [Required]
    [Display(Name = "Your name")]
    public string Name { get; set; }
 
    [Required]
    [Display(Name = "Your IP address")]
    public string IPAddress { get; set; }
 
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        const string regexPattern = @"^([\d]{1,3}\.){3}[\d]{1,3}$";
        var regex = new Regex(regexPattern);
 
        if (!regex.IsMatch(IPAddress))
            yield return new ValidationResult("IP address format is invalid", new[] { "IPAddress" });
    }
}

In this first implementation of the Validate() method I simply check that the given address match an IP V4 format (xxx.xxx.xxx.xxx). I have nothing else to do before being able to test this new behavior in my form.

ip-address-format-error

It works as expected. Yet, the validation is not over since I can put the value 800.800.800.800 (which is not valid for an IP address) without having any error, there is more validation to do:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    const string regexPattern = @"^([\d]{1,3}\.){3}[\d]{1,3}$";
    var regex = new Regex(regexPattern);
 
    if (!regex.IsMatch(IPAddress))
        yield return new ValidationResult("IP address format is invalid", new[] { "IPAddress" });
 
    string[] values = IPAddress.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
 
    byte ipByteValue;
    foreach (string token in values)
    {
        if (!byte.TryParse(token, out ipByteValue))
            yield return new ValidationResult("IP address value is incorrect", new[] { "IPAddress" });
    }
}

I extended the Validate() method in order to add more logic and to check that each element of the IP address has a correct value. I did this by checking that each of them can be transformed into a byte (value from 0 to 255).

ip-address-value-error

By using the IValidatableObject interface I was able to add validation logic to my Model without modifying my Controller. Doing so can be helpful when you have validation logic that depends on several properties of the Model.

In our example I used this interface only to check a single property and therefore it can look a bit “overpowered”. And if I have another form with a IP address field I will need to extract this part of the logic into a specific method to avoid code duplication. This point leads me to my next tip.

Custom attribute

To add validation to a specific field, the IP address one in our case, my advice will be to create a custom validation attribute. This will allow me to put the validation logic in one place only. Here’s the attribute implementation:

public class IpAddressAttribute : RegularExpressionAttribute
{
    public IpAddressAttribute()
        : base(@"^([\d]{1,3}\.){3}[\d]{1,3}$")
    {}
 
    public override bool IsValid(object value)
    {
        if (!base.IsValid(value))
            return false;
 
        string ipValue = value as string;
        if (IsIpAddressValid(ipValue))
            return true;
 
        return false;
    }
 
    private bool IsIpAddressValid(string ipAddress)
    {
        if (string.IsNullOrEmpty(ipAddress))
            return false;
 
        string[] values = ipAddress.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
 
        byte ipByteValue;
        foreach (string token in values)
        {
            if (!byte.TryParse(token, out ipByteValue))
                return false;
        }
 
        return true;
    }
 
    public override string FormatErrorMessage(string name)
    {
        return string.Format("The '{0}' field has an invalid format.", name);
    }
}

The logic is exactly the same as the one present in the IValidatableObject chapter. First checking the overall format with a regular expression and this is why I created a RegularExpressionAttribute subtype. Then the value of each byte is checked. Now I can use this attribute on my Model:

public class IPAddressModel
{
    [Required]
    [Display(Name = "Your name")]
    public string Name { get; set; }
 
    [IpAddress]
    [Required]
    [Display(Name = "Your IP address")]
    public string IPAddress { get; set; }
}

The Controller is unchanged, the Model is much cleaner and I can easily reuse my attribute for each IP address property in my application models without duplicating the logic.

My Model is now fully checked but only on the server-side, and this validation can clearly be done on the client-side as well with some JavaScript. This will avoid unnecessary HTTP requests between the browser and the server.

jQuery validation

ASP .NET now integrates a lot of third-party JavaScript libraries and among them there is jQuery which we will use to achieve client-side validation. I updated the _Layout.cshtml view to add the following lines:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/5.1/jquery.validate.unobtrusive.min.js"></script>

You can find different versions of these script here if you need specific ones. You also have to check that the Web.config is configured in order to enable client-side validation with jQuery:

<configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  ...
</configuration>

I can test the form again and see what is happening.

ip-address-jquery

The data have been checked without posting them to the server. This is possible because the @Html.TextBoxFor() method has generated the following HTML for the IP address field:

<input data-val="true" data-val-required="The Your IP address field is required." id="IPAddress" name="IPAddress" type="text" value="" aria-required="true" class="input-validation-error" aria-describedby="IPAddress-error IPAddress-error" aria-invalid="true">

The data-val-* attributes (HTML5) are used by the jquery.validate plugin to perform the client-side validation. But as you can see, there is nothing related to our regular expression pattern we defined for the IPAddressAttribute. And if you try to validate the form with an invalid IP address the form will still be posted to the server. At the moment the client-site validation is not complete.

IClientValidatable

ASP .NET MVC allow us to extend the generated HTML in order to add more control over the fields in the form. For that I will make the IpAddressAttribute implementing the IClientValidatable interface.

public class IpAddressAttribute : RegularExpressionAttribute, IClientValidatable
{
    public IpAddressAttribute()
        : base(@"^([\d]{1,3}\.){3}[\d]{1,3}$")
    {}
 
    public override bool IsValid(object value)
    {
        // does not change
        ...
    }
 
    private bool IsIpAddressValid(string ipAddress)
    {
        // does not change
        ...
    }
 
    public override string FormatErrorMessage(string name)
    {
        return string.Format("The '{0}' field has an invalid format.", name);
    }
 
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string fieldName = metadata.DisplayName;
        string errorMessage = string.Format("The '{0}' field has an invalid format.", fieldName);
        const string pattern = @"^([\d]{1,3}\.){3}[\d]{1,3}$";
 
        ModelClientValidationRegexRule patternRule = new ModelClientValidationRegexRule(errorMessage, pattern);
        yield return patternRule;
 
        ModelClientValidationRule ipRule = new ModelClientValidationRule();
        ipRule.ValidationType = "ipformat";
        ipRule.ErrorMessage = string.Format("The '{0}' field has an invalid value.", fieldName);
 
        yield return ipRule;
    }
}

This method adds two new validation rule for the client-side code. The first one is for the regular expression and I use the existing ModelClientValidationRegexRule class to do so. The second one is a custom ModelClientValidationRule for which I defined the type as “ipformat”. This means that the input in the form will have a data-val-ipformat attribute.

This attribute is not recognized by the jQuery validation plugin, so I created a IPFormat.js file to extend it:

$.validator.unobtrusive.adapters.addBool("ipformat");
 
$.validator.addMethod("ipformat", function (value, element) {
    if (!value) {
        return false;
    }
    var bytes = value.split(".");
    if (bytes.length != 4) {
        return false;
    }
    for (i in bytes) {
        var entry = bytes[i];
        if (!entry) {
            return false;
        }
        var byte = parseInt(entry);
        if (isNaN(byte) || byte < 0 || byte > 255){
            return false;
        }
    }
    return true;
});

After including this file in my _Layout.cshtm view, I can see that the generated HTML for the text box has changed.

<script src="~/Scripts/Validators/IPFormat.js"></script>
<input data-val="true" data-val-ipformat="The 'Your IP address' field has an invalid value." data-val-regex="The 'Your IP address' field has an invalid format." data-val-regex-pattern="^([\d]{1,3}\.){3}[\d]{1,3}$" data-val-required="The Your IP address field is required." id="IPAddress" name="IPAddress" type="text" value="" aria-required="true" aria-invalid="true" class="input-validation-error" aria-describedby="IPAddress-error">

I now have my attributes for the regular expression validation and for the ipformat validation. Let’s try the form once again.

ip-address-jquery-custom

Here we are, the IP address is fully checked without being sent to the server. To achieve this I only used functionalities present in the framework, such as the IValidatableObject interface, the custom validation attributes, the IClientValidatable interface and a bit of jQuery.

This is the end of this blog post about Model validation in ASP .NET MVC on both server-side and client-side. I hope this will help you and as usual do not hesitate to comment and share this.

See you next time!

Dependency Injection to the rescue

code-coupling

I am a developer, I believe in unit testing and I write a lot of them. But it was not always the case, mostly because I was working on a highly coupled code base. Whenever I wanted to test a single functionality I had to set up a lot of things (database, configuration files, …) to do so even if this functionality was not linked to these dependencies. It was spaghetti code into a big ball of mud.

Then I discovered the Dependency Injection (DI) pattern and it changed the way I designed my code and it made testing much easier. The DI purpose is to reduce coupling between software components in order to improve maintainability and testability. I created the following piece of code to demonstrate the principle :

public class User
{
    public string Name { get; set; }
    public string Email { get; set; }
    public bool HasActivatedNotification { get; set; }
}
 
public class EmailNotifier
{
    public void Notify(User user)
    {
        var message = string.Format("Hello {0} ...", user.Name);
        // Sending email
        // ...
    }
}
 
public class UserRepository
{
    public User GetById(int userId)
    {
        // Fetching information from datasource
        // ...
        return new User { Name = "John", Email = "john@john.com" };
    }
}
 
public class NotificationService
{
    public void NotifyUser(int userId)
    {
        var repository = new UserRepository();
        var user = repository.GetById(userId);
 
        if (user.HasActivatedNotification)
        {
            var notifier = new EmailNotifier();
            notifier.Notify(user);
        }
    }
}

The NotificationService sends an email to a given user if he has activated the notifications. Now if I want to test this logic I will have to set up a datasource for my repository and a mail inbox for the notifier. This is a lot of configuration for a simple piece of logic. This code is highly coupled because the NotifyUser method of my service instantiates its dependencies (the repository and the notifier), this means that the Single Responsibility Principle (SRP) is not respected. I will use the Constructor Injection technique to change the code :

public interface INotifier
{
    void Notify(User user);
}
 
public class EmailNotifier : INotifier
{
    public void Notify(User user)
    {
        var message = string.Format("Hello {0} ...", user.Name);
        // Sending email
        // ...
    }
}
 
public interface IUserRepository
{
    User GetById(int userId);
}
 
public class UserRepository : IUserRepository
{
    public User GetById(int userId)
    {
        // Fetching information from datasource
        // ...
        return new User { Name = "John", Email = "john@john.com" };
    }
}
 
public class NotificationService
{
    public NotificationService(IUserRepository repository, INotifier notifier)
    {
        _repository = repository;
        _notifier = notifier;
    }
 
    private readonly IUserRepository _repository;
    private readonly INotifier _notifier;
 
    public void NotifyUser(int userId)
    {
        var user = _repository.GetById(userId);
 
        if (user.HasActivatedNotification)
        {
            _notifier.Notify(user);
        }
    }
}

The UserRepository and the EmailNotifier are unchanged, they just implement interfaces. Now the NotificationService uses these interfaces as fields that are injected through the constructor. The NotifyUser method can now use these dependencies without having to create them, the code is “cleaner”.

I added interfaces for the repository and the notifier for testing purpose, I can test my service with a fake repository and a fake notifier that do not require heavy configuration :

class MockNotifier : INotifier
{
    public MockNotifier()
    {
        NotifyHasBeenCalled = false;
    }
 
    public bool NotifyHasBeenCalled { get; private set; }
 
    public void Notify(User user)
    {
        NotifyHasBeenCalled = true;
    }
}
 
class MockRepository : IUserRepository
{
    public bool HasValidatedNotification { get; set; }
 
    public User GetById(int userId)
    {
        return new User { HasActivatedNotification = HasValidatedNotification };
    }
}

These two implementations are mocks, it means that they mimic the behavior of concrete classes and are used only for testing purpose. In my MockNotifier I just set a flag to true when the Notify method is called, and the GetById method of the MockRepository returns a User instance with the wanted value for HasActivatedNotification. I created a test class with NFluent to show how it is used :

[TestClass]
public class NotificationServiceTest
{
    private NotificationService _notificationService;
    private MockNotifier _mockNotifier;
    private MockRepository _mockRepository;
 
    [TestInitialize]
    public void TestInit()
    {
        _mockNotifier = new MockNotifier();
        _mockRepository = new MockRepository();
        _notificationService = new NotificationService(_mockRepository, _mockNotifier);
    }
 
    [TestMethod]
    public void NotificationActivated()
    {
        _mockRepository.HasValidatedNotification = true;
        _notificationService.NotifyUser(1);
        Check.That(_mockNotifier.NotifyHasBeenCalled).IsTrue();
    }
 
    [TestMethod]
    public void NotificationDeactivated()
    {
        _mockRepository.HasValidatedNotification = false;
        _notificationService.NotifyUser(1);
        Check.That(_mockNotifier.NotifyHasBeenCalled).IsFalse();
    }
}

I can test the logic of my service without having to configure a datasource with pre-configured users and without checking in a inbox if there is an email or not. Dependency Injection reduces code coupling and makes testing easier even if you have to create dedicated classes for them. You can find more information about DI here and here.

Constructor Injection is a pattern I use because with it I improved the maintainability of my code base with less coupling and more testing, you should try it as well if it’s not the case.

See you next time !

Write clean tests with NFluent

nfluent-logo
NFluent logo

I believe in automated testing. Not only to check that my program works but although as specifications and documentation for my application. When an acceptance test passed you know that the feature is working as it should. Automated tests are also a very good way to document your code and your application, because if the test passed it means that the functionnality is working. And if this functionnality is updated so is the test otherwise it will fail : it is up to date !

At a code level a test let you know how to use the functions/classes you can access and what the return value will be. It is useful when using an external library in your own application. Well, this is a lot of responsibility for a test, so it has to be clear, concise and most of all understandable when read. This is not an easy task but there are some tools that can help you, one of them is NFluent.

Smooth your .NET TDD experience with NFluent! NFluent is an ergonomic assertion library which aims to fluent your .NET TDD experience (based on simple Check.That() assertion statements). NFluent aims your tests to be fluent to write (with a super-duper-happy ‘dot’ auto-completion experience), fluent to read (i.e. as close as possible to plain English. – NFluent team on GitHub.

I used this .NET library for a few months now and I must admit that I just love it ! I just can’t see myself writing unit tests without it, they are easier to write and easier to read. There are a lot of built-in functions based on the type of the value that is checked :

[TestClass]
public class NFluentExamples
{
    [TestMethod]
    public void NFluent_Integer_Examples()
    {
        var sum = Calculator.Add(5, 9);
        Check.That(sum).IsEqualTo(14);
        Check.That(sum).IsNotZero();
        Check.That(sum).IsPositive();
        Check.That(sum).IsLessThan(20);
        Check.That(sum).IsGreaterThan(10);
    }
 
    [TestMethod]
    public void NFluent_String_Examples()
    {
        const string name = "John Doe";
        Check.That(name).IsNotEmpty();
        Check.That(name).IsNotEqualTo("Jane Doe");
        Check.That(name).Contains("John", "Doe");
    }
}

It is also possible to chain the checks the following way  :

int? one = 1;
Check.That(one).HasAValue().Which.IsPositive().And.IsEqualTo(1);

In my last blog post I wrote about exception testing, this is how it is done with NFluent :

[TestMethod]
public void NFluentTest()
{
    Check.ThatCode(() => ClassToTest.IsAQuestion(null)).Throws<NullReferenceException>();
}

You can find a lot more relevant examples on the project website.

Beside making you write cleaner and more readable tests, @NFluent is free, easy to install, open-source and comptatible with your favorite testing frameworks. It is hard to find an excuse for not using it !

NFluent can help you having meaningful tests that become documentation for your application and your public APIs.

See you next time !

Are you a software Boy Scout ?

boy-scout

If you are a developer like me, you probably worked on a legacy code based application. If not, don’t worry (or do) it will certainly happen… We all know a project that we fear to open because it is just a huge mess without a single test and nobody really understand how it works, it just does. Every software team has to work in order to prevent the effects of technical debt.

Refactoring a whole application to make the code “cleaner” can take an enormous amount of time, it can be weeks or sometimes months, depending on the project size and complexity. Some organization will incorporate refactoring phases during the development life-cycle. But since during these periods, the team does not provide any new features (i.e. no value), having these refactoring phases is a hard sell. Time to become a Boy Scout then !

What the boys scouts have to do with software development ? The answer is found in their rule :

“Always leave the campground cleaner than you found it.”

This simple rule can be applied to code and especially legacy code, and it becomes :

“Leave the code better than you found it.”

I present you the Boy Scout Rule (BSR) of programming. Making the code “cleaner” can be done at any moment, and it can be done piece by piece, no need to wait for a “Big Bang Refactoring” phase.

If you have a legacy project it is likely that you will have some improvements or bug fixing to do in it. This is the perfect time to embrace the boy scout philosophy. Of course after your passage the application will still be legacy but a bit less, and the next time you will improve it again. The code will become better with time and one day you’ll stop considering the project as a legacy one.

For example it is possible to rename a variable with a more meaningful name. Given the following code to calculate a triangle area :

var res = b / 2 * h

After the BSR applied :

var triangleArea = base / 2 * height

This is not much but it will help the next developer (maybe you) to understand the code and its purpose. And next time you will see that this piece of code is duplicate in several parts of the code. Time to create a method then :

public int CalculateTriangleArea(int base, int height)
{
    return base / 2 * height;
}

You now have a method that can replace your duplicate code and that can be easily tested with your favorite automated testing framework ! I know that this example is really simple but I’m sure you’ll find these kinds of easy “cleaning” in your applications.

There is a type of code refactoring I often use to make my code more understandable and to ease maintainability : moving repeated magic number value into a single constant variable. For example, a few years back, the french VAT was equal to 19.6% and now it is 20%. I let you imagine the pain it could have been to change every “19.6” in some projects where it could have been far easier to use a single constant with a meaningful name.

There are a lot of refactoring techniques to improve your code base, Martin Fowler gives you a list of some of them here.

A software craftsman does not fear legacy code, by following the Boy Scout Rule he will improve his projects.

See you next time !