SOLID Design Principles

SOLID Design Principles


Single Responsibility Principle(SRP):


A class which follows SRP should have single responsibility just as the name suggests. This will help in making our code easy to change if need be.

Let us go though example which does not follows SRP and which does follow SRP.
There is no limitation on the number of member functions but all the functionality

 i) Below is an example which does not follow SRP

   
 

ii) Below is an example which does follow SRP
   

   
 
In the example above we can see that the responsibility of Open and Close is separated into a different class. Hence we do follow single responsibility principle for ServiceStation Class.

Open Closed Principle (OCP):


OCP states that software application code should be open for extension but closed for modification. Which mean to say that we should be able to extend our code to support more products of a kind without changing the main source code.

Let us again see a sample code which does not follow OCP and the one which does follow OCP.
Let us say our customer asked us to create an application which can calculate the sum of areas of all the rectangles. This seems easy enough and we can do the following without following Open Closed Principle.

i) Without using the Open Closed Principle



















This does not look any bad for the given requirement. But our customer came back to us and asked us to make add area for all circles as well. Now we can expect the customer to come back often and ask us to add many more shapes, here is where we need Open Closed Principle.

ii) Below is the code which uses Open Closed Principle


























Liskov Substitution Principle (LSP):


LSP states that derived classes must be perfectly substitutable for their base classes. This is yet another principle which emphasizes on the use of Interfaces. Let us again see an example where we do use LSP and where do not.

i) Below is an example where we do not use LSP
















ii) Below is an example where we do use LSP




















When we use an interface we get all the methods that are supported in an interface and would adhere to a base class.

Interface Segregation Principle(ISP): 

ISP says we should not force our clients to implement methods which they do not use. For example for a store which has both online and physical store we should not expect to process a credit card using its number unlike an online order.

Let us once again see an implementation which does not follow ISP followed by a one which does follow ISP

i) Below is an example in which we do not follow ISP























ii) Below is a correction to the code above in which we do follow ISP. We create a separate interface for both OnlineOrder and Order















Dependency Inversion Principle(ISP):


If we follow LSP and OCP we will follow ISP. Will add more soon

No comments:

Post a Comment