Decoding SOLID Principles (#1 Single Responsibility)

Shubhi Puntambekar
2 min readMay 10, 2023

SOLID is a very easy word to remember, but remembering the full forms when asked in an interview becomes difficult if not revised well. So if we understand the principles themselves, we can remember the meaning and then recall the full forms.

So let's decode these principles one by one:
S: Single Responsibility
O: Open / Closed
L: Liskov Substitution
I: Interface Segregation
D: Dependency Inversion

So, if you integrate these SOLID principles in your code, your code can be better in terms of the following parameters:
i. More maintainable
ii. Readable and easily understandable
iii. Flexible
iv. Reduced complexity

Single Responsibility Principle

The Single Responsibility Principle states that “A class should have only one responsibility, and it should have only one reason to change.” This boils down to the theory we learned while reading about Classes and Objects. Every object have its attributes and behaviour. So, the class that we are creating should limit its attributes and behaviour to the scope of that particular Object. Let's understand this by an example:

class Item:
def __init__(self, item, price, quantity):
self.item = item
self.price = price
self.quantity = quantity

class Invoice:
def __init__(self, items):
self.items = items

def calculate_total(self):
# do something to calculate total
pass

def print_invoice(self):
# do something to print invoice
pass

def save_to_db(self):
# do something to save to DB.
pass

Now, if you observe that the Invoice class has these functions “print_invoice()” and “save_to_db()” which is not exactly the behavior of an invoice class. An invoice always has a total amount, but it is not exactly the responsibility of the invoice to print itself and save itself in the DB. This doesn’t go with what the Single Responsibility Principle mentions. So let's see how we can fix this.

class Item:
def __init__(self, item, price, quantity):
self.item = item
self.price = price
self.quantity = quantity

class Invoice:
def __init__(self, items):
self.items = items

def calculate_total(self):
# do something to calculate total
pass

class InvoicePrinter:

def print_invoice(self):
# do something to print invoice
pass

class InvoiceDBHelper:

def save_to_db(self):
# do something to save to DB.
pass

Here, we separated the functions in different classes so that every class perform the function which it is responsible for. By this we have achieved the Single Responsibility principle.

Continue reading about the Open/Closed Principle in the next thread by clicking here.

--

--