Interface Segregation Principle (ISP)

Interface Segregation Principle (ISP)

 

Explanation:

A class should not be forced to implement interfaces it does not use.

Real-World Example:

A desktop computer might have a method to plug in a mouse, but a tablet shouldn't be forced to implement this method.

C# Implementation:

 

// Violating ISP
public interface IWorker {
    void Work();
    void Eat();
}

public class Robot : IWorker {
    public void Work() {
        Console.WriteLine("Robot working");
    }
    public void Eat() {
        throw new NotImplementedException("Robots don't eat");
    }
}

// Following ISP
public interface IWorkable {
    void Work();
}

public interface IFeedable {
    void Eat();
}

public class Human : IWorkable, IFeedable {
    public void Work() {
        Console.WriteLine("Human working");
    }
    public void Eat() {
        Console.WriteLine("Human eating");
    }
}

public class Robot : IWorkable {
    public void Work() {
        Console.WriteLine("Robot working");
    }
}

 

Ebook Download
View all
Learn
View all
GE HealthCare will never ask for payment to process documents, refer you to a third party to process