5 SOLID Principles to Write Clean Code

Listen to this Post

Featured Image
Clean code is essential for maintainable, scalable, and efficient software development. The SOLID principles provide a blueprint for writing high-quality code. Here’s a breakdown of each principle with practical applications.

1. Single Responsibility Principle (SRP)

  • Definition: A class or module should have only one reason to change (i.e., one responsibility).
  • Example: A `User` class should handle user properties, while a `UserRepository` class manages database operations.
  • Violation Example:
    class User:
    def <strong>init</strong>(self, name):
    self.name = name</li>
    </ul>
    
    def save_to_db(self):
     Database logic here
    pass
    

    – Corrected Code:

    class User:
    def <strong>init</strong>(self, name):
    self.name = name
    
    class UserRepository:
    def save_to_db(self, user):
     Database logic here
    pass
    

    2. Open-Closed Principle (OCP)

    • Definition: Software entities should be open for extension but closed for modification.
    • Example: Use abstractions (interfaces, abstract classes) to allow new features without altering existing code.
    • Violation Example:
      class Payment:
      def process(self, payment_type):
      if payment_type == "credit":
      Process credit
      elif payment_type == "paypal":
      Process PayPal
      
    • Corrected Code:
      from abc import ABC, abstractmethod</li>
      </ul>
      
      class PaymentProcessor(ABC):
      @abstractmethod
      def process(self):
      pass
      
      class CreditPayment(PaymentProcessor):
      def process(self):
       Process credit
      
      class PayPalPayment(PaymentProcessor):
      def process(self):
       Process PayPal
      

      3. Liskov Substitution Principle (LSP)

      • Definition: Subclasses should be substitutable for their base classes without breaking functionality.
      • Example: If `Bird` is a base class, `Penguin` (which can’t fly) shouldn’t inherit from FlyingBird.
      • Violation Example:
        class Bird:
        def fly(self):
        pass</li>
        </ul>
        
        class Penguin(Bird):
        def fly(self):
        raise Exception("Penguins can't fly!")
        

        – Corrected Code:

        class Bird:
        pass
        
        class FlyingBird(Bird):
        def fly(self):
        pass
        
        class Penguin(Bird):
        def swim(self):
        pass
        

        4. Interface Segregation Principle (ISP)