The SOLID Principles Writing Scalable & Maintainable Code
<p>Has anyone ever told you that you write <em>“bad code”</em>?</p>
<p>Well if you have, there’s really nothing to be ashamed about. We all write flawed code as we learn. The good news is, it’s fairly straightforward to make improvements- but only if you’re willing.</p>
<p>One of the best ways to improve your code is by learning some programming design principles. You can think of programming principles as a general guide to becoming a better programmer- the raw philosophies of code, one could say. Now, there are a whole array of principles out there (one could argue there might even be an overabundance) but I will cover five essential ones which go under the acronym SOLID.</p>
<p><em>Note: I will be using Python in my examples but these concepts are easily transferrable to other languages such as Java.</em></p>
<h2><strong>1. First off… ‘S’ in SOLID stands for Single Responsibility</strong></h2>
<p><img alt="" src="https://miro.medium.com/v2/resize:fit:700/1*enX4PJGzy647ibd-GpSkBQ.png" style="height:409px; width:700px" /></p>
<p>This principle teaches us to:</p>
<blockquote>
<p><strong>Break our code into modules of one responsibility each</strong>.</p>
</blockquote>
<p>Let’s take a look at this <code>Person</code> class which performs unrelated tasks such as sending emails and calculating taxes.</p>
<pre>
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def send_email(self, message):
# Code to send an email to the person
print(f"Sending email to {self.name}: {message}")
def calculate_tax(self):
# Code to calculate tax for the person
tax = self.age * 100
print(f"{self.name}'s tax: {tax}")</pre>
<p>According to the <strong>Single Responsibility Principle</strong>, we should split the <code>Person</code> class up into several smaller classes to avoid violating the principle.</p>
<p><a href="https://forreya.medium.com/the-solid-principles-writing-scalable-maintainable-code-13040ada3bca">Visit Now</a></p>