Know the Importance of SOLID Principles

Gopal Date: December 14, 2019

SOLID Principle is the most important part of object-oriented programming language.  It is introduced by Robert C. Martin is also known as Uncle Bob who is an American software engineer and instructor. The main purpose of the SOLID principle is to make your software or application more understandable, easier to extend and maintain. In simple words, we normally write code to get our work and don’t think about its future stability. When our application or software needs to scale, that time we put our hands up or write a whole application from scratch or make code messy to serve its purpose due to poorly written code. To overcome this sort of problem, SOLID Principle has been introduced.

The SOLID Stands for:

S – Single-responsibility principle

O – Open-closed principle

L – Liskov substitution principle

I – Interface segregation principle

D – Dependency Inversion Principle

Single Responsibility Principle:

S in SOLID Principle stands for Single Responsibility Principle (SRP). SRP is one of the most important concepts in object-oriented design. SRP states that a class should have one and only one reason to change. A very clear understanding is that we are working on API which receives requests, authenticates the user, validates the data, query on the database, format the data and then send back the response. In such a case SRP tells that do all the operations in separate classes but it should be like that making all the functions in a single file. It would be childish work if we keep everything in one place and make messy our code. One more thing is that this is what we normally do, so how to use SRP in our application. Let’s take an example, we have a crud class and in which we are performing add, edit, delete and show operation. This is a normal class but if we need to print the data then we will make function print but in case, print can be in raw format, Json format, Html format and so on. So we will make such functions, if we make such functions in crud class then it violate SRP principle. The main reason behind is that a crud class perform curd operation and other format function should be handled in other classes.

Lets take an example, without SRP:

<?php

Class Book
{
	public $title; 

	public $author; 

	public function setTitle()
	{
		$this->title = 'Object Oriented Design Patterns';
	}

	public function getTitle()
	{
		return $this->title;
	}

	public function setAuthor()
	{
		$this->author = 'Gopal Kumar';
	}

	public function getAuthor()
	{
		return $this->author;
	}

	public function print()
	{
		// print book content
	}
}

With SRP

<?php

implements Printer
{
	function print($book);
}

Class HtmlPrinter implements Printer
{
	function print(Book $book)
	{
		echo "<h1>{$book->getTitle()}</h1>";
	}
}

Class JsonPrinter implements Printer
{
	function print(Book $book)
	{
		echo json_encode([
			'title' => $book->getTitle()
		]);
	}
}