
SOLID: Principles of Object-Oriented Programming
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 = None4 self.data = None56 def load_data(self):7 # Code to load data from a file8 pass910 def train(self):11 # Code to train the model12 pass1314 def predict(self):15 # Code to make predictions using the model16 pass17
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 file4 pass56class ModelTrainer:7 def __init__(self, data):8 self.data = data9 self.model = None1011 def train(self):12 # Code to train the model13 pass1415class Predictor:16 def __init__(self, model):17 self.model = model1819 def predict(self):20 # Code to make predictions using the model21 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_type5 elif loaded_type == 'API':6 self.loaded_type = loaded_type7 elif loaded_type == 'CSV':8 self.loaded_type = loaded_type910 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()171819 def _load_from_sql(self):20 # Code to load data from SQL database21 pass22 def _load_from_api(self):23 # Code to load data from an API24 pass25 def _load_from_csv(self):26 # Code to load data from a CSV file27 pass2829
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, abstractmethod23class DataLoader(ABC):4 @abstractmethod5 def load_data(self):6 pass789class SQLDataLoader(DataLoader):10 def load_data(self):11 # Code to load data from SQL database12 pass1314class APIDataLoader(DataLoader):15 def load_data(self):16 # Code to load data from an API17 pass1819class CSVDataLoader(DataLoader):20 def load_data(self):21 # Code to load data from a CSV file22 pass2324# Usage25def get_data(loader: DataLoader):26 return loader.load_data()2728## SQL29sql_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:
12class DataLoader:3 def load_data(self):4 pass56 def transform_data(self, data):7 pass89class SQLDataLoader(DataLoader):10 def load_data(self):11 return [{"id": 1, "raw_value": "100"}]1213 def transform_data(self, data):14 return [{"id": d["id"], "value": int(d["raw_value"])} for d in data]1516class PreprocessedLoader(DataLoader):17 def load_data(self):18 return [{"id": 1, "value": 100}]1920 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 @abstractmethod3 def load_data(self):4 pass56 class Transformable(ABC):7 @abstractmethod8 def transform_data(self, data):9 pass1011 class SQLDataLoader(DataLoader, Transformable):12 # carga y transforma1314 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 pass45 def train_model(self, data):6 # Code to train the model7 pass89 def get_feature_importance(self):10 # Code to calculate feature importance11 pass1213class XGBoostHandler(ModelsHandler):14 def train_model(self, data):15 # Code to train the XGBoost model16 pass1718 def get_feature_importance(self):19 # Code to calculate feature importance for XGBoost20 pass2122class LinealRegression(ModelsHandler):23 def train_model(self, data):24 # Code to train the LightGBM model25 pass2627 def get_feature_importance(self):28 # Code to calculate feature importance for LightGBM29 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, abstractmethod2class ModelsHandler(ABC):3 @abstractmethod4 def train_model(self, data):5 pass678class XGBoostHandler(ModelsHandler):9 def train_model(self, data):10 # Code to train the XGBoost model11 pass1213 def get_feature_importance(self):14 # Code to calculate feature importance for XGBoost15 pass1617class LinealRegression(ModelsHandler):18 def train_model(self, data):19 # Code to train the LightGBM model20 pass21
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 SQL4 pass567class RouterOptimizer:8 def __init__(self):9 self.data_source = DataSourceSQL()1011 def optimize(self):12 # Code to optimize routing based on data13 pass1415 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, abstractmethod234class DataSourceInterface(ABC):5 @abstractmethod6 def load_data(self, data):7 pass8910class DataSourceSQL(DataSourceInterface):11 def load_data(self, data):12 # Code to load and preprocess data13 pass1415class DataSourceAPI(DataSourceInterface):16 def load_data(self, data):17 # Code to load and preprocess data18 pass192021class RouterOptimizer:22 def __init__(self, data_source: DataSourceInterface):23 self.data_source = data_source2425 def optimize(self):26 # Code to optimize routing based on data27 pass2829 def run(self, data):30 processed_data = self.data_source.load_data(data)31 return self.optimize(processed_data)323334api_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/