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.