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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more