SOLID: Interface Segregation Principle

multi-cablesIn my latest posts I introduced the Single Responsibility Principle, the Open Closed Principle and the Liskov Substitution Principle of SOLID. Now it is time to see the Interface Segregation Principle (ISP). In Object Oriented Programming (OOP) abstraction is a valuable asset especially with interfaces that allow you to design your application by contracts. Even if the interfaces do not contain any actual code it is important to control their size. The following sentence defines the ISP rule:

Clients should not be forced to depend on methods they do not use.

In other words it means that you should have small dedicated interfaces instead of larger ones. This way the client code will only have access to the functionalities it needs. I have created an example to show how the ISP can be violated and how to fix it.

public interface IRepository<T> where T : class
{
    void Insert(T entity);
    void Update(T entity);
    T Get(int id);
    void Delete(int id);
}

I have this interface that represents a repository to manipulate the entities stored in my database, it has the basic CRUD (Create Read Update Delete) operations. I will use this interface on my User entity:

public class User
{
    public int Id { get; set; }
    // other properties
}
 
public class UserRepository : IRepository<User>
{
    public void Insert(User entity)
    {
        // save user in DB
    }
 
    public void Update(User entity)
    {
        // update user in DB
    }
 
    public User Get(int id)
    {
        // retrieve user from DB
        return new User();
    }
 
    public void Delete(int id)
    {
        // delete user from DB
    }
}

Good, I have now a full control over my User objects lifetime in the database. Now I also want to be able to retrieve some event logs to be able to consult them, I will use my repository interface to do so.

public class EventLog
{
    public int Id { get; set; }
    public string Message { get; set; }
    // other properties
}
 
public class LogRepository : IRepository<EventLog>
{
    public void Insert(EventLog entity)
    {
        // nothing to do
    }
 
    public void Update(EventLog entity)
    {
        // nothing to do
    }
 
    public EventLog Get(int id)
    {
        // retrieve log from DB
        return new EventLog();
    }
 
    public void Delete(int id)
    {
        // nothing to do
    }
}

The issue is that my logs are stored in the database by other applications and in the one I’m working on I don’t have any logging to do. This force me to leave 3 methods empty since they are not used but are defined in my interface… This is clearly a violation of the Interface Segregation Principle. In this example I have a repository that is “read & write” and another that is just “read”. My abstraction is not correct in my context.

I have to find a solution that allows me to keep the functionalities for both repositories without breaking the ISP. I will then create two separate interfaces:

public interface IReadRepository<T> where T : class
{
    T Get(int id);
}
 
public interface IWriteRepository<T> where T : class
{
    void Insert(T entity);
    void Update(T entity);
    void Delete(int id);
}

As you can see one is dedicated to “read” operations and the other to “write” operations. My LogRepository can now inherits the IReadRepository because it does not need anything else.

public class LogRepository : IReadRepository<EventLog>
{
    public EventLog Get(int id)
    {
        // retrieve log from data source
        return new EventLog();
    }
}

And what about the UserRepository? Since it is “read & write” it will implement both interfaces. Multiple inheritance is commonly use when the ISP is in play.

public class UserRepository : IReadRepository<User>, IWriteRepository<User>
{
    public void Insert(User entity)
    {
        // save user in DB
    }
 
    public void Update(User entity)
    {
        // update user in DB
    }
 
    public User Get(int id)
    {
        // retrieve user from DB
        return new User();
    }
 
    public void Delete(int id)
    {
        // delete user from DB
    }
}

With time my application is likely to grow and use more and more entities from the database that will need “read” and “write” operations. If it is the case I can create an IReadWriteRepository that will be defined like this:

public interface IReadWriteRepository<T> : IReadRepository<T>, IWriteRepository<T>
    where T : class
{
 
}

In my example the UserRepository can implement this interface since it works as an alias over the two other ones. The ISP does not prevent you from regrouping interfaces under a common one. This will allow your code to be “cleaner” and explicit without losing functionalities.

This is the end of the Interface Segregation Principle presentation, remember to look for partial implementations of an interface if you want to spot where the ISP is violated.

I hope you liked this 4th principle of the SOLID series and as always do not hesitate to share, comment and give your opinion.

See you next time!

SOLID: Liskov Substitution Principle

lego-duploIt is time for the third entry for the SOLID series, after the SRP and the OCP, I’ll introduce the Liskov Substitution Principle (LSP). This concept has been introduced by Barbara Liskov in 1984, with Jeannette Wing they define this principle as the following:

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S, where S is a subtype of T.

Well, if you are like me you must be still trying to figure this one out to understand how it can be applied to Object Oriented Programming. Do not worry, a more accessible rule has been defined to specify the LSP.

Subtypes must be substitutable for their base types.

In other words it means that consuming any implementation of a base class should not change the correctness of the system. To give more depth to this principle I will use the famous Rectangle-Square example to show how this rule can be violated.

public class Rectangle
{
    public int Width { get; set; }
    public int Length { get; set; }
    public virtual int CalculateArea()
    {
        return Width * Length;
    }
}
 
public class Square : Rectangle
{
    public override int CalculateArea()
    {
        return Width * Width;
    }
}

As you can see, the Square is a subclass of Rectangle and that makes sense since a square is a rectangle with the same width and length. Now I will use these two classes in a program:

class Program
{
    static void Main(string[] args)
    {
        Rectangle rectangle = new Square();
        rectangle.Length = 10;
        rectangle.Width = 5;
        Console.WriteLine("Area : {0}", rectangle.CalculateArea());
    }
}
Area: 25

Let me resume the situation: I have a rectangle of 10 by 5 and its area is 25?! This does not make sense. Even if the inheritance seems legitimate, the way it is used in my application violates the Liskov Substitution Principle.

Using the NotSupportedException of the .NET framework is likely showing that the LSP is not respected in your source code. There is even a part of this same framework that transgress this principle.

class Program
{
    static void Main(string[] args)
    {
        ICollection<int> collection = new ReadOnlyCollection<int>(new List<int>{1,2});
        collection.Add(3);  // throws a NotSupportedException
    }
}

The ReadOnlyCollection does not allow any modification to the collection, it is impossible to add or remove items in it. Yet its the ICollection interface that defines methods to manipulate the items: the LSP is clearly violated.

The LSP is closely related to the Design by Contract approach to create software. This way your thinking ahead of the pre-conditions,  post-conditions and side effects for your application and every implementations of your subtypes are related to your contracts.

This is the end of the introduction to the Liskov Substitution Principle and especially how to detect when the rule is broken. I am still working on a relevant example to demonstrate how to start from a “bad” code sample, like the ones I gave you, to a sample that respect the LSP.

In the meantime do not hesitate to give your opinion regarding this topic.

See you next time!

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!

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 !

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 !

Meet your community

community

About a year ago I watched a video made by Scott Hanselman and Rob Conery entitled “Get Involved !”. The purpose of this video is to convince software developers to become active within their community. I really enjoyed this video and it made me want to participate more. This blog is the first example of the things I did toward this goal.

If you want to find more information about this subject and watch the video : Become a Social Developer !

There is a whole chapter related to user groups which allowed me to discover Meetup. This network helps you find user groups in your area in almost any domain you like. This way you can meet people who share common hobbies and interests. And if there is a subject you like without a related meetup in your neighborhood, nothing stop your from creating it !

I recently attended my first meetup and it was an extraordinary experience, I came across a lot of interesting people I could not have been able to meet otherwise. It was all about debating, discussing and sharing in a funny and respectful way. The subject of this meetup was Software Craftsmanship and you can find a summary I wrote on my company’s blog here.

I can only highly recommend Meetup to find communities you might want to socialize with.

See you next time !