SOLID: Open Closed Principle

dutch-door

In my last entry I introduced the S of the SOLID principles: Single Responsibility Principle. Today I will move to the next letter, the O which stands for Open Closed Principle. In an agile environment, teams and projects have to be responsive to change (4th value of the agile manifesto) in order to steadily add value (2nd value of the software craftsmanship manifesto). But respecting these values can be really hard if the code of your application is not easily extensible. This is where this second principle come in play.

Software entities (classes, modules, functions, etc…) should be open for extension but closed for modification.

This is the rule for the Open Closed Principle. There are 2 key attributes in this statement and in the name of the principle as well: open & close. Even if they are in opposition this does not imply that they block each other.

The module is open for extension, this means that it can be extended with new behaviors as the requirements for the application change. Yet the module is also closed for modification, in other words it implies that you should be able to extend the functionalities of this module without modifying its source code. I know it might sound confusing and this is why I’ll show an example to explain how this principle can be used.

public class User
{
    // some properties
}
 
public class NotificationCenter
{
    public void NotifyByEmail(User user, string message)
    {
        // some email related logic
    }
 
    public void NotifyByText(User user, string message)
    {
        // some texting relating logic
    }
}

In this piece of code I created a class that allows me to send notifications to a user by email or by text. Now imagine that I want my application to notify my users using social networks… I will have to modify the source code of this class to add new behaviors and it clearly violates the OCP. I will update my class in order to change this “mistake”:

public interface INotificationService
{
    void SendMessage(User user, string message);
}
 
public class EmailNotificationService : INotificationService
{
    public void SendMessage(User user, string message)
    {
        // some email related logic
    }
}
 
public class TextNotificationService : INotificationService
{
    public void SendMessage(User user, string message)
    {
        // some texting related logic
    }
}

public class FacebookNotificationService : INotificationService
{
    public void SendMessage(User user, string message)
    {
        // some facebook related logic
    }
}
 
public class TwitterNotificationService : INotificationService
{
    public void SendMessage(User user, string message)
    {
        // some twitter related logic
    }
}
 
public class NotificationCenter
{
    public void Notify(User user, string message, INotificationService service)
    {
        // some logic
        service.SendMessage(user, message);
    }
}

My NotificationCenter now use a specific interface to do its work and I am able to add functionalities to it without changing the code. All I have to do is to implement the INotificationService to add a new behavior. By doing this I can even separate each implementation in a specific assembly and I avoid putting Facebook or Twitter dependencies in my class. For instance if the Twitter API changes and I have to change the code, I can only package and deliver the TwitterNotificationService, I don’t have to redeploy everything.

The key to the OCP is abstraction. Yet this does not mean that you have to use it everywhere, the context is important and premature abstraction may add complexity to your source code where it is not needed.

I hope you like this presentation of the Open Closed Principle for the SOLID series. You can also check this great article by Joel Abrahamsson about this principle.

See you next time!

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!

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 !