Single Responsibility Principle in Python | by Erdem Isbilen | Jun, 2022


With easy to follow explanations for the beginners

Photo by Dmitriy on Unsplash

Getting software to work and making software clean are two very different activities — Robert C.Martin (Clean Code)

While coding, you can easily get carried away by the tasks at hand, and only focus on getting your code to work. As a result, you lost track of lines you are adding to your code, and end up with bulky, not organised, yet working functions.

The single responsibility principle is a software design guideline which states that every module, class or function in your code should have only one responsibility and only one reason to change.

This principle is all about organising the complexity of your code, gathering together the things that change for the same reasons so that you know where to look to modify things without considering all the complexity involved.

Read on to learn more about the single responsibility principle, why and how it is implemented in Python.

If you follow the single responsibility principle, you will end up with a large number of small functions, or classes instead of large ones.

You may think that this may not be a good idea. And perhaps you prefer a few large functions and classes.

Obviously, if you follow this principle blindly and break down your code into atomic sections, this also leads to some undesired side effects. There should be a balancing consideration, and the below quote defines what it is;

Gather together the things that change for the same reasons. Separate those things that change for different reasonsRobert C.Martin

Why following the single responsibility principle is a good idea;

  • It helps to transform a large block of code into well-defined, well-labelled, high cohesive, clean and robust components.
  • It requires you to name more code blocks and forces you to be specific about your intentions. This makes your code much more readable over time.
  • It is easy to spot duplicate code when your functions and classes are as small as possible.
  • Small and well-defined code blocks can be mixed and re-used better.
  • Small functions are easy to test and easy to understand by others.
  • It becomes easy to see when a function doesn’t belong in a namespace.
  • Spending time to identify unique responsibilities helps us recognize and create better abstractions in our code.
Photo by Austin Distel on Unsplash

Single Responsibility Principle — Python Classes:

You can see the Model class below has a way to many responsibilities. Pre-processing data, training and evaluating the model, making predictions are different responsibilities that are all handled in Model class. This is against the single responsibility principle and is strongly not advised due to the reasons highlighted above.

# Before the single responsibility principleclass Model:

def pre_process(self):
pass

def train(self):
pass

def evaluate(self):
pass

def predict(self):
pass

As shown below, we can create separate classes handling each of the responsibilities to make our class compatible with the single responsibility principle.

# After the single responsibility principle appliedclass PreProcess:
pass
class Train:
pass
class Evaluate:
pass
class Predict:
pass

Single Responsibility Principle — Python Functions:

When it comes to functions, it is even more important to follow single responsibility principle. I always find myself handling many tasks in a single function body which makes the function bulky and not unorganized.

# Before the single responsibility principle applieddef pre_processing_data():
#importing data
#converting data types
#handling missing values
#handling outliers
#transforming data

Now, once we handle each task in a separate function, we can have much cleaner, easy to mix and re-use functions compared the first one.

# After the single responsibility principle applieddef import_data(): 
pass
def convert_data_type():
pass
def handle_missing_values():
pass
def handle_outliers():
pass
def transform_data():
pass

The key takeaways are;

  • The single responsibility principle is a software design guideline which states that every module, class or function in your code should have only one responsibility and only one reason to change.
  • It helps to transform a large block of code into well-defined, well-labelled, high cohesive, clean and robust components.
  • Small and well-defined code blocks can be mixed and re-used better.

I hope you have found the article useful and will start applying the single responsibility principle in your own code.


With easy to follow explanations for the beginners

Photo by Dmitriy on Unsplash

Getting software to work and making software clean are two very different activities — Robert C.Martin (Clean Code)

While coding, you can easily get carried away by the tasks at hand, and only focus on getting your code to work. As a result, you lost track of lines you are adding to your code, and end up with bulky, not organised, yet working functions.

The single responsibility principle is a software design guideline which states that every module, class or function in your code should have only one responsibility and only one reason to change.

This principle is all about organising the complexity of your code, gathering together the things that change for the same reasons so that you know where to look to modify things without considering all the complexity involved.

Read on to learn more about the single responsibility principle, why and how it is implemented in Python.

If you follow the single responsibility principle, you will end up with a large number of small functions, or classes instead of large ones.

You may think that this may not be a good idea. And perhaps you prefer a few large functions and classes.

Obviously, if you follow this principle blindly and break down your code into atomic sections, this also leads to some undesired side effects. There should be a balancing consideration, and the below quote defines what it is;

Gather together the things that change for the same reasons. Separate those things that change for different reasonsRobert C.Martin

Why following the single responsibility principle is a good idea;

  • It helps to transform a large block of code into well-defined, well-labelled, high cohesive, clean and robust components.
  • It requires you to name more code blocks and forces you to be specific about your intentions. This makes your code much more readable over time.
  • It is easy to spot duplicate code when your functions and classes are as small as possible.
  • Small and well-defined code blocks can be mixed and re-used better.
  • Small functions are easy to test and easy to understand by others.
  • It becomes easy to see when a function doesn’t belong in a namespace.
  • Spending time to identify unique responsibilities helps us recognize and create better abstractions in our code.
Photo by Austin Distel on Unsplash

Single Responsibility Principle — Python Classes:

You can see the Model class below has a way to many responsibilities. Pre-processing data, training and evaluating the model, making predictions are different responsibilities that are all handled in Model class. This is against the single responsibility principle and is strongly not advised due to the reasons highlighted above.

# Before the single responsibility principleclass Model:

def pre_process(self):
pass

def train(self):
pass

def evaluate(self):
pass

def predict(self):
pass

As shown below, we can create separate classes handling each of the responsibilities to make our class compatible with the single responsibility principle.

# After the single responsibility principle appliedclass PreProcess:
pass
class Train:
pass
class Evaluate:
pass
class Predict:
pass

Single Responsibility Principle — Python Functions:

When it comes to functions, it is even more important to follow single responsibility principle. I always find myself handling many tasks in a single function body which makes the function bulky and not unorganized.

# Before the single responsibility principle applieddef pre_processing_data():
#importing data
#converting data types
#handling missing values
#handling outliers
#transforming data

Now, once we handle each task in a separate function, we can have much cleaner, easy to mix and re-use functions compared the first one.

# After the single responsibility principle applieddef import_data(): 
pass
def convert_data_type():
pass
def handle_missing_values():
pass
def handle_outliers():
pass
def transform_data():
pass

The key takeaways are;

  • The single responsibility principle is a software design guideline which states that every module, class or function in your code should have only one responsibility and only one reason to change.
  • It helps to transform a large block of code into well-defined, well-labelled, high cohesive, clean and robust components.
  • Small and well-defined code blocks can be mixed and re-used better.

I hope you have found the article useful and will start applying the single responsibility principle in your own code.

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – admin@technoblender.com. The content will be deleted within 24 hours.
artificial intelligenceErdemIsbilenJunPrinciplepythonresponsibilitySingleTech NewsTechnoblender
Comments (0)
Add Comment