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):