DEV Community

sumandari
sumandari

Posted on

SOLID principles (Python) in my simple understanding

Nowadays, I have been learning SOLID principle in python.

S: Single responsibility principle -- A class/ module must have only one role.

O: Open/Closed principle -- open to extension but closed to modification. This can be achieved by using an interface (a base/ mixin class that can be used polymorphically). We don't modify the base class itself, instead, we create new interfaces to full fill the requirements.

L: Liskov substitution principle -- different parts of a program can be used interchangeably, as long as they behave in the same way. e.g. Each car class has different properties, like its speed and handling, but they all behave in a similar way, because they all have to move around the track and avoid crashing.

I: Interface segregation principle -- interfaces should be small. Small enough to only do one thing but still contains methods needed. e.g: When you create a mixing class with context manager logic, it should contain at least two methods: __enter__ and __exit__. They must go together, or the outcome will not be a valid context manager at all.

D: Dependency inversion principle -- high-level modules should not depend on low-level modules. Rather, both should depend on abstractions. Using general ideas instead of specific details to make it easier to modify and add new features to a program.

references:

  • Clean Code in Python - Second Edition by Mariano Anaya

Top comments (0)