avatarErdem Isbilen

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2757

Abstract

i>It is easy to spot duplicate code when your functions and classes are as small as possible.</li><li>Small and well-defined code blocks can be mixed and re-used better.</li><li>Small functions are easy to test and easy to understand by others.</li><li>It becomes easy to see when a function doesn’t belong in a namespace.</li><li>Spending time to identify unique responsibilities helps us recognize and create better abstractions in our code.</li></ul><figure id="ef47"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*Pr4L0cMJ_NN2HMGw"><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h1 id="d601">Python Implementation of Single Responsibility Principle</h1><h2 id="6453">Single Responsibility Principle — Python Classes:</h2><p id="a942">You can see the <b>Model</b> 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 <b>Model</b> class. This is against the single responsibility principle and is strongly not advised due to the reasons highlighted above.</p><div id="e19f"><pre><span class="hljs-comment"># Before the single responsibility principle</span></pre></div><div id="4c49"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">Model:

<span class="hljs-symbol">def</span></span> <span class="hljs-symbol">pre_process</span>(<span class="hljs-symbol">self</span>): <span class="hljs-symbol">pass</span></pre></div><div id="2e33"><pre> <span class="hljs-keyword">def</span> <span class="hljs-title function_">train</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): pass

<span class="hljs-keyword">def</span> <span class="hljs-title function_">evaluate</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): pass</pre></div><div id="4c59"><pre> <span class="hljs-keyword">def</span> <span class="hljs-title function_">predict</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): pass</pre></div><p id="ece5">As shown below, we can create separate classes handling each of the responsibilities to make our class compatible with the single responsibility principle.</p><div id="5f85"><pre><span class="hljs-comment"># After the single responsibility principle applied</span></pre></div><div id="3f2b"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">PreProcess: <span class="hljs-symbol">pass</span></span></pre></div><div id="454

Options

8"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">Train: <span class="hljs-symbol">pass</span></span></pre></div><div id="79d6"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">Evaluate: <span class="hljs-symbol">pass</span></span></pre></div><div id="db13"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">Predict: <span class="hljs-symbol">pass</span></span></pre></div><h2 id="dbb9">Single Responsibility Principle — Python Functions:</h2><p id="7352">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.</p><div id="986e"><pre><span class="hljs-comment"># Before the single responsibility principle applied</span></pre></div><div id="5e8a"><pre>def pre_processing_data(): #importing <span class="hljs-built_in">data</span> #converting <span class="hljs-built_in">data</span> types #handling missing values #handling outliers #transforming <span class="hljs-built_in">data</span></pre></div><p id="b2c6">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.</p><div id="bb67"><pre><span class="hljs-comment"># After the single responsibility principle applied</span></pre></div><div id="e572"><pre><span class="hljs-title">def</span> import_data(): pass</pre></div><div id="eee8"><pre><span class="hljs-title">def</span> convert_data_<span class="hljs-keyword">type</span>(): pass</pre></div><div id="4a4e"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">handle_missing_values</span>(): pass</pre></div><div id="00c1"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">handle_outliers</span>(): pass</pre></div><div id="9e12"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">transform_data</span>(): pass </pre></div><h1 id="f4c2">Key Takeaways and Conclusion</h1><p id="49a2">The key takeaways are;</p><ul><li>The <b>single responsibility principle</b> is a software design guideline which states that every <b>module</b>, <b>class</b> or <b>function</b> in your code should have <b>only one responsibility and only one reason to change</b>.</li><li>It helps to transform a large block of code into<b> well-defined, well-labelled, high cohesive, clean and robust components</b>.</li><li>Small and well-defined code blocks can be mixed and re-used better.</li></ul><p id="272d">I hope you have found the article useful and <b>will start applying the single responsibility principle in your own code</b>.</p></article></body>

Single Responsibility Principle in Python

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.

Benefits of applying the Single Responsibility Principle

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

Python Implementation of Single Responsibility Principle

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 principle
class 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 applied
class 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 applied
def 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 applied
def import_data(): 
  pass
def convert_data_type(): 
  pass
def handle_missing_values(): 
  pass
def handle_outliers(): 
  pass
def transform_data(): 
  pass

Key Takeaways and Conclusion

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.

Python
Single Responsibility
Design Principles
Data Science
Coding
Recommended from ReadMedium