SOLID Principles Explained with Examples

Listen to this Post

S: Single Responsibility Principle (SRP)

A class should have one and only one reason to change.

❌ Bad: A `UserManager` class that handles authentication, user profiles, and email notifications.

βœ… Better: Break it into separate classes:

– `UserAuthenticator` (handles authentication)
– `UserProfileManager` (manages user profiles)
– `EmailNotifier` (sends emails)

This keeps each class focused, improving maintainability.

O: Open/Closed Principle (OCP)

Software entities should be open for extension but closed for modification.

❌ Bad: A `ShapeCalculator` class that requires modification every time a new shape is added.
βœ… Better: Use a `Shape` base class and extend it with subclasses (Rectangle, Triangle, etc.). Now, new shapes can be added without modifying existing code.

L: Liskov Substitution Principle (LSP)

Objects of a superclass should be replaceable with objects of its subclasses.

❌ Bad: A `Bicycle` class inheriting from Vehicle, but overriding a `startEngine()` method that makes no sense for bicycles.
βœ… Better: Use a more general `start()` method in Vehicle. This way, `Car` and `Bicycle` can be used interchangeably without unexpected behavior.

I: Interface Segregation Principle (ISP)

No client should be forced to depend on interfaces they don’t use.

❌ Bad: A `MediaPlayer` interface that requires all implementations to support both audio and video, even when unnecessary.
βœ… Better: Split into `AudioPlayer` and `VideoPlayer` interfaces. Now, classes implement only what they need, making the code more flexible.

D: Dependency Inversion Principle (DIP)

High-level modules should not depend on low-level modules; both should depend on abstractions.

❌ Bad: An `EmailService` class that directly depends on a GmailClient.
βœ… Better: Introduce an `EmailClient` interface. Now, `EmailService` depends on the abstraction, allowing support for multiple providers (GmailClient, OutlookClient, etc.) without code changes.

You Should Know:

To implement these principles in practice, here are some verified commands and steps:

1. Single Responsibility Principle (SRP):

  • Use modular programming in Python:
    class UserAuthenticator: 
    def authenticate(self, username, password): </li>
    </ul>
    
    <h1>Authentication logic</h1>
    
    class UserProfileManager: 
    def update_profile(self, user_id, profile_data):
    
    <h1>Profile update logic</h1>
    
    class EmailNotifier: 
    def send_email(self, user_id, message):
    
    <h1>Email sending logic</h1>
    
    

    2. Open/Closed Principle (OCP):

    • Extend classes in Java:
      abstract class Shape { 
      abstract double area(); 
      } </li>
      </ul>
      
      class Rectangle extends Shape { 
      double area() { 
      // Rectangle area logic 
      } 
      }
      
      class Triangle extends Shape { 
      double area() { 
      // Triangle area logic 
      } 
      } 
      

      3. Liskov Substitution Principle (LSP):

      • Use polymorphism in C#:
        public class Vehicle { 
        public virtual void Start() { 
        // General start logic 
        } 
        } </li>
        </ul>
        
        public class Car : Vehicle { 
        public override void Start() { 
        // Car start logic 
        } 
        }
        
        public class Bicycle : Vehicle { 
        public override void Start() { 
        // Bicycle start logic 
        } 
        } 
        

        4. Interface Segregation Principle (ISP):

        • Split interfaces in TypeScript:
          interface AudioPlayer { 
          playAudio(): void; 
          } </li>
          </ul>
          
          interface VideoPlayer { 
          playVideo(): void; 
          }
          
          class MusicPlayer implements AudioPlayer { 
          playAudio() { 
          // Audio playback logic 
          } 
          } 
          

          5. Dependency Inversion Principle (DIP):

          • Use dependency injection in Python:
            from abc import ABC, abstractmethod </li>
            </ul>
            
            class EmailClient(ABC): 
            @abstractmethod 
            def send(self, message): 
            pass
            
            class GmailClient(EmailClient): 
            def send(self, message):
            
            <h1>Gmail sending logic</h1>
            
            class OutlookClient(EmailClient): 
            def send(self, message):
            
            <h1>Outlook sending logic</h1>
            
            class EmailService: 
            def <strong>init</strong>(self, client: EmailClient): 
            self.client = client
            
            def send_email(self, message): 
            self.client.send(message) 
            

            What Undercode Say:

            The S.O.L.I.D principles are foundational for writing clean, maintainable, and scalable code. By adhering to these principles, developers can avoid common pitfalls such as tightly coupled code, rigid architectures, and unmanageable systems. Here are some additional Linux and Windows commands to help you implement these principles in real-world scenarios:

            • Linux Commands:
            • Use `grep` to search for specific patterns in your codebase:
              grep -r "class UserManager" /path/to/codebase 
              
            • Use `find` to locate files that need refactoring:
              find /path/to/codebase -name "*.py" -exec grep -l "Single Responsibility" {} \; 
              

            • Windows Commands:

            • Use `dir` to list files in a directory:
              [cmd]
              dir C:\Projects\Codebase /s /p
              [/cmd]
            • Use `findstr` to search for specific patterns in files:
              [cmd]
              findstr /s /i “Open/Closed Principle” *.cs
              [/cmd]

            By combining these principles with practical commands, you can streamline your development process and produce high-quality software.

            Expected Output:

            • Clean, modular, and maintainable code.
            • Reduced technical debt and improved scalability.
            • Enhanced team collaboration and code readability.

            For further reading, visit: blog.algomaster.io

            References:

            Reported By: Ashishps1 Solid – Hackers Feeds
            Extra Hub: Undercode MoN
            Basic Verification: Pass βœ…

            Join Our Cyber World:

            πŸ’¬ Whatsapp | πŸ’¬ TelegramFeatured Image