Single Responsibility Principle

This is episode 1 on my SOLID design principle series. Single Responsibility Principle is the S of SOLID principles.

Uncle Bob says,

A class should have only one reason to change

In case of module or class it should concern about a single responsibility, and in case of method or function it should do a single thing.

Unix commands are best example of this principles. ls command will list directory contents.

In OOP we often put everything under a class. For example lets say we have a Bookclass that has title, author and current_page properties.

In the Book class we can see it has all sort of rendering logic in it, it seems fine at first glance but if we look carefully why a plain Book class have to know about all those rendering logic, what if we need another type of rendering tomorrow ? should we just go ahead and change this class ? it seems dual responsibility.

Instead we can extract the rendering logic into its own class, first lets define a RendererInterface that declares a render method.

Now we can implement it for text and web rendering as follows.

and the client would use it like

This is a very basic example of how we can separate responsibilities around classes, one thing to note that it would require to add more classes but it would be slim! so the takeaway is

many thin classes are better than one big fat class

Thats all I have for now!