Reputation: 1768
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
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:
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
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