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 !

Keep control of your entities

Today I want to share tips to improve the control you have over your code and especially over your entities in a Oriented Object language. The example will be in C# .NET.

During my (still short) career I’ve been  working on a certain amount of projects and I often found the same practices related to entities : they are just PODS !

Here’s an example with an Invoice, a Product and a Customer entities.

public class Product
{
    public UInt16 Id { get; set; }
    public string Name { get; set; }
}
 
public class Customer
{
    public string Name { get; set; }
}
 
public class Invoice
{
    public Product Product { get; set; }
    public Customer Customer { get; set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine("{0} ordered :", Customer.Name);
        Console.WriteLine("{0} - {1}", Product.Id, Product.Name);
    }
}

Now, let’s use these classes in a program :

class Program
{
    static void Main(string[] args)
    {
        Invoice invoice = new Invoice();
        invoice.DisplayInfo();
    }
}

And yes, this program throws a NullReferenceException when displaying the invoice because my Invoice.Customer instance is NULL. Let’s fix our Invoice class the following way.

public class Invoice
{
    public Invoice()
    {
        Product = new Product();
        Customer = new Customer();
    }
 
    public Product Product { get; set; }
    public Customer Customer { get; set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine("{0} ordered :", Customer.Name);
        Console.WriteLine("{0} - {1}", Product.Id, Product.Name);
    }
}

But this time the program class looks like this :

class Program
{
    static void Main(string[] args)
    {
        Invoice invoice = new Invoice();
        invoice.Customer = null;
        invoice.DisplayInfo();
    }
}

The NullReferenceException still occurs because the Customer is set to NULL. I know you wonder why I did this… Because the code structure allows me to do it ! It might look stupid this way but sometimes in a more complex application you can set an object’s property to NULL without knowing it, if you’re calling an external service for example or another provider.

Let’s change our Invoice class again to use a bit of encapsulation.

public class Invoice
{
    public Invoice(Product product, Customer customer)
    {
        Product = product;
        Customer = customer;
    }
 
    public Product Product { get; protected set; }
    public Customer Customer { get; protected set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine("{0} ordered :", Customer.Name);
        Console.WriteLine("{0} - {1}", Product.Id, Product.Name);
    }
}

With this version the Customer and the Product have to be set when constructing the Invoice. So ? Do you think we’re done ? Let’s find out with a new program.

class Program
{
    static void Main(string[] args)
    {
        Invoice invoice = new Invoice(null, null);
        invoice.DisplayInfo();
    }
}

Still not running correctly, still the same exception for the exact same reason. You can add control to your entities properties but you should add control during initialization as well to avoid manipulating an invalid instance of your class.

This lead us to our final version of the Invoice class (at least in this post).

public class Invoice
{
    public Invoice(Product product, Customer customer)
    {
        if (product == null)
            throw new ArgumentNullException("product");
        if (customer == null)
            throw new ArgumentNullException("customer");
 
        Product = product;
        Customer = customer;
    }
 
    public Product Product { get; protected set; }
    public Customer Customer { get; protected set; }
 
    public void DisplayInfo()
    {
        Console.WriteLine("{0} ordered :", Customer.Name);
        Console.WriteLine("{0} - {1}", Product.Id, Product.Name);
    }
}

I choose to use the ArgumentNullException to prevent the construction of an invalid object. This allow me to have a complete control on my Invoice entity. With these kind of practices I try to prevent incorrect behavior from misuse. I transformed a PODS into an entity with “intelligence”.

I hope these tips will help you and do not hesitate to share yours and/or to comment about these tips.

See you next time for more software development related topics !