An introduction to Single Responsibility principle (SRP)

This is the fifth and last article describing SOLID principles. This article is about the Single Responsibility principle. Hopefully it will help you understand what the principle is all about and why it’s important to keep it in mind when designing and writing your code.

What is the Single Responsibility principle?

Here is the definition from Wikipedia: The term was introduced by Robert C. Martin in an article by the same name as part of his Principles of Object Oriented Design, made popular by his book Agile Software Development, Principles, Patterns, and Practices. Martin described it as being based on the principle of cohesion, as described by Tom DeMarco in his book Structured Analysis and Systems Specification. Continue reading →

An introduction to Open Closed principle (OCP)

This is the fourth article on SOLID principles which I started a few weeks ago. I hope this is useful for you and that it gives you a simple understanding of what the Open/Closed principle is all about.

What is the Open Closed principle?

Bertrand Meyer coined the term Open/Closed Principle which appeared in his book titled Object Oriented Software Construction in 1988. The principle reads “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification“. Continue reading →

An introduction to Liskov substitution principle (LSP)

This post is about the Liskov substitution principle (LSP). This is also the third of my posts about SOLID principles, following the posts I wrote about DI and ISP in the past few weeks.

What is Liskov substitution principle (LSP)?

This principle is based on Barbara Liskov’s definition of subtyping, commonly known as the Liskov substitution principle which states the following:

if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program

or in my own words, in programming we cannot always represent our objects with real-life objects and so we need to make sure subtypes respect their parents. Using the illustration below, in order to follow this principle we need to make sure that the subtypes (duck, cuckoo, ostrich) respect the parent class (bird). This means that in our code, we should be able to replace bird with duck, cuckoo or ostrich.

Subtyping

The above illustration shows clearly how in object-oriented programming (OOP) we can reuse some of our classes by making use of inheritance. This also shows very simply how using a base/parent class can be very beneficial and it is a main part of OOP.

So what is the problem you might ask? what is the purpose of the Liskov substitution principle? the purpose of it is to help you avoid some problems when modeling your objects by making you aware of potential problems that aren’t so obvious when using inheritance at the time of development.

The idea is to keep the LSP in mind when developing our classes so a parent class like “bird” can point to any of its child class objects i.e. “duck”, “cuckoo” or “ostrich” during runtime without any issues.

A classic example of LSP violation

One of the most classic examples of LSP violation is the use of a Rectangle class as the parent of a Square class. At first it seems this is the right thing to do as in Mathematics a square is a rectangle. However, in code this is not always true and this is what I meant when I wrote above that you cannot model your objects in code as you would do in the real world.

Below is an example of how in code, something like deriving a class of type Square from a Rectangle class might seem ideal…

public class Rectangle
 {
    public double Height { get; set; }
    public double Width { get; set; }
 }

 public class Square : Rectangle
 {
    public Square CreateSquare(double w)
    {
       var newSquare = new Square
       {
          Height = w, Width = w
       };
       return newSquare;
    }
 }

The example above looks fine, you can call the method CreateSquare by passing a value which is then assigned to both the height and width values of the object, this results in a proper formed square where all sides are equal. The problem arises when you define a rectangle where the height and width have different values, if you then try to substitute that object using a Square object… you will get unexpected results as the Square object expects its height and width properties to have the same value all the time.

However, the Liskov substitution principle says that you should be able to substitute any of the child classes for its base class and the example of the rectangle/square clearly breaks that rule.

The Liskov Susbtitution Principle (LSP) is one of the SOLID principles which can help you during software development to avoid common mistakes that are hard to notice if you are not thinking about them when using inheritance and modeling your classes/objects.

Happy coding!

An introduction to Interface Segregation Principle (ISP)

Last week I wrote a post about Dependency Injection (DI) with some basic examples in C#. Today I would like to write and offer a simple example of what is known as Interface Segregation Principle (ISP) which can happen if you are not careful when using and implementing interfaces in your code.

What is Interface Segregation Principle (ISP)?

The goal behind ISP is that no client consuming an interface should be forced to depend on methods it does not use. For example, you might have a class that implements an interface called IPersist. Let’s call it ReservationDatabase, and this class has code that persists a hotel reservation details to a database. IPersist contains the public method declaration of the method in ReservationDatabase that performs the persistence to the database. IPersist looks like this:

public interface IPersist
 {
    bool Save(ReservationDetails reservation);
 }

As you can see, this interface is very simple and it only has one responsibility. You could implement this from several classes that have a public method labeled “Save” to save some data to a database, to a XML document, to other data repository, etc… Everything is good so far.

Now, let’s say that you have a new class for logging some of the tasks related to the reservation, and you would like this ReservationLog class to implement IPersist as well as one of the functions of ReservationLog is to save this to a log repository. To implement IPersist you simply add the following at the top of your class:

public class ReservationLog : IPersist

This is the entire ReservationLog class that now implements IPersist:

public class ReservationLog : IPersist
 {
    public bool Save(ReservationDetails reservation)
    {
       // imagine some code here to perist data to database...
       return true;
    }

    public void Log(ReservationDetails reservation)
    {
       // imagine some code here to log to a log repository
    }

    public void SendNotification(ReservationDetails reservation)
    {
       // imagine some code here that notifies about logging
    }
 }

Now, since we are already implementing IPersist in our ReservationLog class which has two other methods, we update IPersist so it includes the two other methods from ReservationLog because it will be easier for the class or classes consuming IPersist to access these methods when logging is needed. So the updated IPersist interface looks like this now:

public interface IPersist
 {
    bool Save(ReservationDetails reservation);
    void Log(ReservationDetails reservation);
    void SendNotification(ReservationDetails reservation);
 }

What we did above might not look like a big change but it is. What we did above is wrong if you didn’t first carefully consider the consequences of implementing IPersist in a class that has multiple public methods and then adding those new method declarations to IPersist. The main responsibility of IPersist was until now to abstract the details from classes that allowed to save reservation details to some data repository. By implementing IPersist on ReservationLog and adding all of its public method declarations to this interface, the result is broken code in all of the classes that are implementing IPersist IF they don’t have public methods that match with those in the IPersist interface.

For example, the original ReservationDatabase class looks like this:

public class ReservationDatabase : IPersist
 {
    public bool Save(ReservationDetails reservation)
    {
       // imagine some code here to persist data to database...
       return true;
    }
 }

This code won’t compile anymore as this class and perhaps other classes in our code that implement IPersist, do not have methods that implement the two new declarations we added to IPersist:

void Log(ReservationDetails reservation);
void SendNotification(ReservationDetails reservation);

The common and not recommended “fix” for this is to “implement” these methods in all classes that implement IPersist and then just return a not implemented exception if anyone ever uses it. Using our example, our ReservationDatabase will look like this if we apply the quick fix:

public class ReservationDatabase : IPersist
 {
    public bool Save(ReservationDetails reservation)
    {
       // imagine some code here to persist data to database...
       return true;
    }
    public void Log(ReservationDetails reservation)
    {
       throw new NotImplementedException();
    }
    public void SendNotification(ReservationDetails reservation)
    {
       throw new NotImplementedException();
    }
 }

The code above is a clear example of breaking the interface segregation principle, which advises not to force any client to depend on methods that it does not use… like the two methods in our illustration above. If you ever see code like this in your projects, where the methods are implementing an interface and all its methods and just throwing NotImplementedException errors on some of them, the code is breaking the interface segregation principle. It is bad as the fix is quite simple and by fixing it you will end up with more maintainable code that can be easier to read and debug.

How to avoid violating the ISP principle?

It is actually very easy, it does require a bit more work but in the end you will have better organized code, you will be following this principle and a few more such as single responsibility and the universal KISS principle.

If you wanted to implement IPersist in your ReservationLog class you can still do it. However, do not update IPersist to accomodate for the other public methods in your ReservationLog class, instead create a new interface, implement it and use it to add any log related methods from your class to it. This is what this new interface might look like:

public interface ILog
{
   void Log(ReservationDetails reservation);
   void SendNotification(ReservationDetails reservation);
}

Now you can implement ILog in your ReservationLog class. You can do this by adding a comma and typing the name of it after IPersist which was implemented earlier.

public class ReservationLog : IPersist, ILog

That’s it! by doing this you can still implement IPersist without having to change other classes that might implement it and you also create a new interface that can be used by any classes wanting to implement the Log and SendNotification methods.

You could probably remove the SendNotification method and abstract it to yet another interface named INotify to keep your code simple, organized and maintainable.

Also, if your code is already violating ISP and you have interfaces that already have multiple method declarations then your should consider fixing this by refactoring your code using the Adapter pattern, take a look at this to see a clear example of it.

Hope this is useful to you. Happy coding!

 

An introduction to Dependency Injection (DI) and Inversion of Control (IoC)

There is so much confusion and arguing about what dependency injection is and whether is the same as inversion of control or just one form of it. If you are new to these terms it can be very confusing to say the least. I’ll try to describe what these are with some examples written in C# and hopefully you’ll have a better understanding of what this is and how to actually implement them in your code.

Dependency Injection (DI) vs. Inversion of Control (IoC)

According to Martin Fowler these two are exactly the same thing, here is some text extracted from his own article about inversion of control:

As a result I think we need a more specific name for this pattern. Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection.

Based on this I have personally settled on calling it all Dependency Injection which can be implemented in different forms. So, what is Dependency Injection? my definition of it? instead of having your classes creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor or via property setters, and your class doesn’t care about much else. This helps you to decouple dependencies that your classes are dependent on to do their work to make your code more flexible and testable.

For example, let’s say we have a booking service which we use to create a reservation object when a traveler books a hotel in a website. The reservation class might include things like validation and other business logic but it also calls code from another class to save the reservation details to a database. Here is an illustration of what I just described: mockup The photo above shows how the Reservation class depends on the ReservationDatabase class. In other words, Reservation knows that it needs a ReservationDatabase instance in order to be able to save the reservation details. The question to ask is, does the Reservation class really needs to know that it uses ReservationDatabase? It should be enough that Reservation class knows about the behavior, the methods, properties etc, of ReservationDatabase without knowing who actually implements that behavior. Let’s take a look at the code representation of the above:

public class Reservation
    {
        public void ProcessReservations(ReservationDetails reservation)
        {
            // business logic, validation, etc...

            // save booking to database
            new ReservationDatabase().Save(reservation);
        }
    }

Now, imagine if you wanted to test the code in the Reservation class, it wouldn’t work as in the example above uses an instance of ReservationDatabase which has the code to save the reservation to the database. In other words, you would need a database to test the code above. Also, the code above is not very flexible as it forces one class to know about the class that implements some of the code. For example, if you wanted to unit test the Reservation class you would need to test the code behind the Save method too as it is a method used in the code above. You cannot isolate your code using the implementation above.

Applying Dependency Injection

With dependency injection we can solve the potential problems we described above and with a few simple changes our code can be more flexible and testable. We can isolate our code and decouple our classes so one does not have to know the details of the other, just needs to know about the interface and not the class that implements it at run time. So how we do this? We can remove the dependency of Reservation on ReservationDatabase by extracting an abstract definition of the behavior used by Reservation in ReservationDatabase, in other words, let’s create an Interface to separate the two classes and ‘hide’ the implementation details of ReservationDatabase to the Reservation class. This is illustrated below: dependencyinjection In the illustration above, ReservationDatabase implements IPersist (interface) and Reservation uses it. At this point Reservation might still be using ReservationDatabase but it doesn’t know it, it just knows that is uses something that implements IPersist. We could change what happens in ReservationDatabase and the Reservation class wouldn’t know about it, or perhaps we could have a new class implement IPersist and again, Reservation wouldn’t know or care about it. Here is the code representation of the above, first you’ll see how Reservation now uses the new interface IPersist which is implemented by ReservationDatabase in our example:

public class Reservation
    {
        private IPersist _reservationDatabase;

        public Reservation(IPersist reservationDatabase)
        {
            this._reservationDatabase = reservationDatabase;
        }

        public void ProcessReservations(ReservationDetails reservation)
        {
            // business logic, validation, etc...

            // save booking to database
            _reservationDatabase.Save(reservation);
        }
    }

The code above shows you a basic implementation of Dependency Injection (DI), now let’s see how we benefit from this. The code above shows how we injected the dependency (IPersist) into our Reservation class by using a constructor. We did this by using what is called constructor injection, where we supply the IPersist instance to Reservation’s constructor, or property injection where we supply it to Reservation after it has been instantiated by setting a property on it.

This gives us the ability to use any code that implements IPersist without knowing the details of that code. For example, let’s say that we wanted to not only persist the reservation to the database but also to some XML document for whatever reason. With the updated code we would just need to write a new class that had all of the code to create a new XML document and then make sure that implements our interface IPersist. By doing this, our Reservation class will now be able to save the reservation data to XML without having to make any code changes in that class. See illustration below:

dependencyinjectionThe above illustration shows clearly how Reservation only needs to know about IPersist but it doesn’t know what other classes implement it, and that is OK. As you would imagine, we could keep adding classes to perform some sort of persistence without having to make a single change on Reservation, all we need to do is implement IPersist and we’ll be done.

Dependency injection in this example is what we showed in the code example above, notice how Reservation has a constructor which requires an instance of IPersist as a parameter. It stores this instance in a field and when invoked the last step of ProccessReservations method uses this injected instance to save the reservation.

I will write about Dependency Injection Containers / IoC Containers in a follow up post but for now, use the examples above as a basic way to implement Dependency Injection in your code to make it a bit more flexible and testable. Cheers!