SOLID: Principles of Object-Oriented Programming

SOLID: Principles of Object-Oriented Programming

Francisco

-
Follow me on
linkedin icongithub icon
Published on Jan 29, 2026

Predicting the future is becoming increasingly difficult—especially in programming. We know that today many people who write code use assistants in their daily work. In expert hands, these tools can increase productivity exponentially rather than becoming a threat.

Nevertheless, responsibility still lies with us. We are the ones who must validate, question, and test what assistants produce, based on our own experience and knowledge. Today, more than ever, topics such as programming fundamentals, design patterns, concepts, and experience are excellent tools for questioning what machines do, guiding them with the necessary human touch to build real, meaningful solutions.

Because of my background, I was never deeply exposed to patterns or “proper” ways of writing code. However, during my time studying abroad, I have come across ideas that I find genuinely interesting (and that, if you are a programmer, you were probably taught at university). These ideas can help others build more robust and solid solutions. Programming has been a well-studied discipline since the 1930s, with Alan Turing as one of its pioneers. Like any industry, it has developed theoretical frameworks, patterns, frameworks, and different programming languages over time.

Python is one of the most popular programming languages today, largely due to its strong object-oriented orientation and high readability, which allow even non-technical people to learn and work with it. An object-oriented language is based on the concept of objects, where classes are represented as objects (nouns) and their actions are methods (the things those objects can do).

Based on this paradigm, five core principles were defined:

  • Single Responsibility Principle (SRP)
  • Open–Closed Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

Each of these principles corresponds to a letter, and together they form the word SOLID.

In this article, I will discuss these principles and explain why they are important for building high-quality solutions.


Single Responsibility Principle (SRP)

The first principle is the Single Responsibility Principle (SRP), introduced by Robert C. Martin. It is defined as follows:

A class should have only one reason to change.

This means that a class should have only one responsibility, expressed through its methods. If a class performs more than one task, we should split it into two dedicated classes with different names. This may sound a bit abstract, but let’s imagine the following idea, expressed in the code below:

1class MLOService:
2 def __init__(self):
3 self.model = None
4 self.data = None
5
6 def load_data(self):
7 # Code to load data from a file
8 pass
9
10 def train(self):
11 # Code to train the model
12 pass
13
14 def predict(self):
15 # Code to make predictions using the model
16 pass
17

Let’s imagine that we are building a machine learning pipeline, and we have a single class that handles the entire process—from data extraction to model training and making predictions. This class feels awkward: it does too many things, and everything is tightly packed into a single object.

A good practice would be to break the problem down into smaller parts, creating separate classes for each responsibility. If we refactor this code, it would look something like the following.

1class DataLoader:
2 def load_data(self):
3 # Code to load data from a file
4 pass
5
6class ModelTrainer:
7 def __init__(self, data):
8 self.data = data
9 self.model = None
10
11 def train(self):
12 # Code to train the model
13 pass
14
15class Predictor:
16 def __init__(self, model):
17 self.model = model
18
19 def predict(self):
20 # Code to make predictions using the model
21 pass

The refactoring has made the code much more modular, separating responsibilities into individual classes and allowing future changes to adapt naturally to the class structure. This is considered a good practice because it breaks the problem down into smaller pieces and allows each class to exist as a separate object, focusing on what it does best, rather than relying on a single global class that tries to handle everything.

Open–Closed Principle (OCP)

The second principle is called the Open–Closed Principle, and it was introduced by Bertrand Meyer in 1998. This principle states:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

At first glance, this may not be entirely clear, but its core idea is that any class should be written in such a way that it can be used as it is. A class can be extended (enhanced), but it should not be modified. In simple terms, you can change a class’s behaviour by adding new code, not by altering the existing one.

An example of this principle could be the following:

1class DataLoader:
2 def __init__(self, loaded_type):
3 if loaded_type == 'SQL':
4 self.loaded_type = loaded_type
5 elif loaded_type == 'API':
6 self.loaded_type = loaded_type
7 elif loaded_type == 'CSV':
8 self.loaded_type = loaded_type
9
10 def load_data(self):
11 if self.loaded_type == 'SQL':
12 return self._load_from_sql()
13 elif self.loaded_type == 'API':
14 return self._load_from_api()
15 elif self.loaded_type == 'CSV':
16 return self._load_from_csv()
17
18
19 def _load_from_sql(self):
20 # Code to load data from SQL database
21 pass
22 def _load_from_api(self):
23 # Code to load data from an API
24 pass
25 def _load_from_csv(self):
26 # Code to load data from a CSV file
27 pass
28
29

The problem with this code is that it works perfectly for the data types that were originally defined, but it fails when a new type of data is introduced. If you need to add another data source, you would have to modify the existing class instead of simply adding something new.

One way to solve this issue is the following:

1from abc import ABC, abstractmethod
2
3class DataLoader(ABC):
4 @abstractmethod
5 def load_data(self):
6 pass
7
8
9class SQLDataLoader(DataLoader):
10 def load_data(self):
11 # Code to load data from SQL database
12 pass
13
14class APIDataLoader(DataLoader):
15 def load_data(self):
16 # Code to load data from an API
17 pass
18
19class CSVDataLoader(DataLoader):
20 def load_data(self):
21 # Code to load data from a CSV file
22 pass
23
24# Usage
25def get_data(loader: DataLoader):
26 return loader.load_data()
27
28## SQL
29sql_loader = SQLDataLoader()
30data = get_data(sql_loader)

In this case, the code has been modularised using a DataLoader class, which defines a load_data method. This method is not explicitly implemented, but instead serves as a contract that subclasses can implement in their own way, such as SQLDataLoader, APIDataLoader, and so on. If a new data extraction method is required, a new subclass can be added without modifying the existing code.

Liskov Substitution Principle (LSP)

This principle was introduced by Barbara Liskov at the OOPSLA conference in 1987. It states the following:

Subtypes must be substitutable for their base types.

In simple terms, this principle means that if you have a piece of code that works with a given class, then any subclass should be able to replace that base class without breaking the code. In other words, subclasses must be able to use the methods of the parent class while preserving the expected behaviour.

This idea is illustrated in the following code:

1
2class DataLoader:
3 def load_data(self):
4 pass
5
6 def transform_data(self, data):
7 pass
8
9class SQLDataLoader(DataLoader):
10 def load_data(self):
11 return [{"id": 1, "raw_value": "100"}]
12
13 def transform_data(self, data):
14 return [{"id": d["id"], "value": int(d["raw_value"])} for d in data]
15
16class PreprocessedLoader(DataLoader):
17 def load_data(self):
18 return [{"id": 1, "value": 100}]
19
20 def transform_data(self, data):
21 raise NotImplementedError("Data ya viene transformada")
22

If we consider that PreprocessedLoader is a class that already contains pre-processed data, it makes no sense for it to include a method that transforms the data (transform_data), since the data already comes processed directly from the source.

Because of this, it is better to design two separate classes in the following way:

1class DataLoader(ABC):
2 @abstractmethod
3 def load_data(self):
4 pass
5
6 class Transformable(ABC):
7 @abstractmethod
8 def transform_data(self, data):
9 pass
10
11 class SQLDataLoader(DataLoader, Transformable):
12 # carga y transforma
13
14 class PreprocessedLoader(DataLoader):
15 # solo carga, no promete transformar

Interface Segregation Principle (ISP)

The Interface Segregation Principle (ISP) follows the same underlying idea as the Single Responsibility Principle. Its main objective is:

Clients should not be forced to depend upon methods that they do not use. Interfaces belong to clients, not to hierarchies.

A client can be understood as a class or subclass, and an interface as the set of methods and attributes it exposes. In simple terms, if a class does not use a particular method or attribute, that method should belong to a different interface or class.

An illustrative example of this principle is the following:

1class ModelsHandler:
2 def __init__(self):
3 pass
4
5 def train_model(self, data):
6 # Code to train the model
7 pass
8
9 def get_feature_importance(self):
10 # Code to calculate feature importance
11 pass
12
13class XGBoostHandler(ModelsHandler):
14 def train_model(self, data):
15 # Code to train the XGBoost model
16 pass
17
18 def get_feature_importance(self):
19 # Code to calculate feature importance for XGBoost
20 pass
21
22class LinealRegression(ModelsHandler):
23 def train_model(self, data):
24 # Code to train the LightGBM model
25 pass
26
27 def get_feature_importance(self):
28 # Code to calculate feature importance for LightGBM
29 raise NotImplementedError("Fax functionality not supported")
30

This code has a problem: ModelHandler includes a method that cannot be implemented consistently across all subclasses—especially for a linear regression model.

The way to solve this is the following:

1from abc import ABC, abstractmethod
2class ModelsHandler(ABC):
3 @abstractmethod
4 def train_model(self, data):
5 pass
6
7
8class XGBoostHandler(ModelsHandler):
9 def train_model(self, data):
10 # Code to train the XGBoost model
11 pass
12
13 def get_feature_importance(self):
14 # Code to calculate feature importance for XGBoost
15 pass
16
17class LinealRegression(ModelsHandler):
18 def train_model(self, data):
19 # Code to train the LightGBM model
20 pass
21

The new ModelsHandler class now contains only the train_model method, leaving any additional behaviour to the subclasses rather than the parent class. This is the correct way to solve this problem. If a model has a specific function, it should be declared only for that model and should not affect others.

Dependency Inversion Principle (DIP)

This principle states the following:

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

This can be a bit difficult to explain purely in words, so an example should help to illustrate it more clearly.

1class DataSourceSQL:
2 def load_data(self, data):
3 # Code to load and preprocess data from SQL
4 pass
5
6
7class RouterOptimizer:
8 def __init__(self):
9 self.data_source = DataSourceSQL()
10
11 def optimize(self):
12 # Code to optimize routing based on data
13 pass
14
15 def run(self, data):
16 processed_data = self.data_source.load_data(data)
17 return self.optimize(processed_data)
18

Here we have a delivery route optimisation algorithm that relies on a database to build the most optimal route. In this code, the RouteOptimizer class depends directly on the DataSource class. However, if we add another data source, we would have to modify both the optimiser and DataSource.

This behaviour is not ideal, so the way to solve it is the following:

1from abc import ABC, abstractmethod
2
3
4class DataSourceInterface(ABC):
5 @abstractmethod
6 def load_data(self, data):
7 pass
8
9
10class DataSourceSQL(DataSourceInterface):
11 def load_data(self, data):
12 # Code to load and preprocess data
13 pass
14
15class DataSourceAPI(DataSourceInterface):
16 def load_data(self, data):
17 # Code to load and preprocess data
18 pass
19
20
21class RouterOptimizer:
22 def __init__(self, data_source: DataSourceInterface):
23 self.data_source = data_source
24
25 def optimize(self):
26 # Code to optimize routing based on data
27 pass
28
29 def run(self, data):
30 processed_data = self.data_source.load_data(data)
31 return self.optimize(processed_data)
32
33
34api_source = DataSourceAPI()
35optimizer = RouterOptimizer(api_source)
36optimizer.run(data)

In this new approach, the DataSource class is defined as an interface. As a result, any new data source can be added without affecting the route optimisation algorithm, effectively removing the dependency described earlier.

Conclusion

Best practices and frameworks act as reference models. Although they are not always followed strictly, it is important to know and understand them. These principles have been iterated on and tested over time, and they continue to stand as excellent industry standards.

References:

1: https://www.youtube.com/playlist?list=PL4CE9F710017EA77A .

2: https://www.youtube.com/watch?v=agkWYPUcLpg&t=1s

3: https://realpython.com/solid-principles-python/


Ir arriba