Open/Closed Principle (OCP)

Open/Closed Principle (OCP)

The Open/Closed Principle states that a class, module, or function should be open for extension but closed for modification.

Explanation:
This means that software components should be designed in a way that allows new behavior to be added without changing existing code. Instead of modifying classes directly, extend their behavior using inheritance, interfaces, or composition.

Why it's important:

  • Prevents breaking existing functionality when adding new features
  • Supports scalable and maintainable code
  • Enables developers to add new use cases with minimal risk

Bad Example (Violates OCP):

public class NotificationService

{

    public void SendNotification(string type)

    {

        if (type == "Email")

            SendEmail();

        else if (type == "SMS")

            SendSMS();

    }

 

    private void SendEmail() { /* send email */ }

    private void SendSMS() { /* send SMS */ }

}

Adding a new notification type like Push requires modifying the existing method.

Good Example (Follows OCP):

public interface INotifier

{

    void Send();

}

 

public class EmailNotifier : INotifier

{

    public void Send() { /* send email */ }

}

 

public class SMSNotifier : INotifier

{

    public void Send() { /* send SMS */ }

}

 

public class NotificationService

{

    private readonly INotifier notifier;

 

    public NotificationService(INotifier notifier)

    {

        this.notifier = notifier;

    }

 

    public void Notify()

    {

        notifier.Send();

    }

}

Now new types of notifications can be added by creating new classes that implement INotifier — without modifying NotificationService.

 

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced