20
Back to Basics: SOLID Principles (Part 1)
SOLID is an acronym for the 5 programming principles which stands for:
- Single Responsibility Principle
- Open Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
Why should you care about these principles you ask?
These principles help you in changing one area of the software without impacting others. Basically, they’re intended to make the code easier to understand, maintain, and extend.
This post is just Part 1 of the series, Back to Basics, each covering one SOLID principle.
A class should have one and only one reason to change which means it should only have one job.
If a class has more than one responsibility then changing one responsibility results in modifications in other responsibilities.
Let's take an example:
class Animal:
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
def save(self, animal):
"""Saves the animal details to DB"""
pass
Now the Animal class has two responsibilities:
- Maintain the properties of the animal
- Save the animal details in a database
If the application changes in a way that it affects the database management functions, for example: save() function, then the classes that use the properties of the Animal class will have to be updated and recompiled.
Solution?
We create another class which will handle all the database management responsibilities.
class AnimalDB:
def save(self, animal):
"""Saves the animal details to DB"""
pass
def get_animal(self, _id):
"""Gets the animal details by _id from the DB"""
pass
class Animal:
def __init__(self, name):
self.name = name
self._db = AnimalDB()
def get_name(self):
"""Get animal name"""
return self.name
def save(self):
"""Saves the animal to DB"""
self._db.save(animal=self)
At the time of designing our classes, we should always put related features together so whenever they tend to change they change for the same reason and try to separate the features that will change for different reasons.
20