Moh'd Awad
Moh'd Awad

Reputation: 1768

What is the difference between the ISP and the OCP?

I don't understand what the difference is between the Interface Segregation Principle and the Open/Closed Principle.

What I understand is that the ISP must make everything depend on interfaces and the OCP on classes and I see that both of them can be implemented in the same way but one with interfaces and one with classes.

Upvotes: 0

Views: 908

Answers (2)

Arkadiusz K
Arkadiusz K

Reputation: 1827

Programming to interfaces tell us that our code should depend on interfaces , while ISP guides us to not create god interfaces that have large amount of methods. Large interfaces causes two major problems:

  • clients using that interface depend on methods that they don't use
  • new implementations of that interface must implement every method , and if interface is large it's not always clear how to properly implement that interface

OCP guides us to write code that we can extend without modifying existing code. So, for example let assume that you have following interface:

public interface ITask
{
    void Execute();
} 

Then you create SendToEmailTask class that implements ITask interface. Assume that after some time new requirement shows up that you need add logging to SendToEmailTask. And according to OCP you should not modify existing code but rather add new LoggingTask that also implements ITask interface (using Decorator pattern):

public class LoggingTask : ITask
{
    private readonly ITask task;

    public LoggingTask(ITask task)
    {
         //guard clause
         this.task = task;
    }

    public void Execute() 
    { 
        Logger.Log("task...");
        this.task.Execute();
    }
} 

Thanks to that you also achieved Single Responsibility principle.

Upvotes: 4

Mark Shevchenko
Mark Shevchenko

Reputation: 8207

Lets look at principles from a perspective of a unit test development.

If you write a lot of unit tests for a single interface/class, it's like you violate the ISP principle. The interface is a too large.

If you want to override some method in testing interface/class, but you can't do it cause this method is not virtual, it's like you violate the OCP principle and your class doesn't allow an extention.

Upvotes: 0

Related Questions