S.O.L.I.D Principles in Python

Radhakrishnan Selvaraj
2 min readJul 1, 2022

--

SOLID principles makes your code more extendable, logical, and easier to read.

Single Responsibility Principle:

“A class should have one, and only one, reason to change”

All the properties and methods should work only for one responsibility. The calculator class responsibility is to perform only the mathematical operation, not to set an alarm.

reader.py — Reader class should perform the read operations not write operations.

Open-Closed Principle:

“Classes, functions, modules should be open for extension, but closed for modifications”

In the below example we are extending the Reader class to FileReader and JDBCReader without modifying the Reader class.

Liskov Substitution Principle:

“Objects of a superclass should be replaceable with objects of its subclasses without breaking the application”

The Liskov substitution principle states that a child class must be substitutable for its parent class. Liskov substitution principle aims to ensure that the child class can assume the place of its parent class without causing any errors.

Interface Segregation Principle:

“A client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.”

Make fine grained interfaces that are client-specific. Client can use multiple interfaces when required.

In the below example, Transform class is a client which uses Reader and Writer Interfaces.

Dependency Inversion Principle:

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Abstractions should not depend on details. Details should depend on abstractions.

The below examples shows the tightly and loosely coupled classes.

Thanks for reading!

For more about SOLID : Solid Python

--

--