SOLID Principles

Example 2: Worker Example

Consider a more complex example with workers who perform different tasks.

Violating ISP

public interface IWorker
{
    void Work();
    void Eat();
}

public class Worker : IWorker
{
    public void Work()
    {
        // Working logic
    }

    public void Eat()
    {
        // Eating logic
    }
}

public class Robot : IWorker
{
    public void Work()
    {
        // Working logic
    }

    public void Eat()
    {
        throw new NotImplementedException();
    }
}

In this example, the Robot class is forced to implement the Eat method, which is not relevant for robots.

Adhering to ISP

public interface IWorker
{
    void Work();
}

public interface IHumanWorker : IWorker
{
    void Eat();
}

public class Worker : IHumanWorker
{
    public void Work()
    {
        // Working logic
    }

    public void Eat()
    {
        // Eating logic
    }
}

public class Robot : IWorker
{
    public void Work()
    {
        // Working logic
    }
}

In this design, IWorker is a more focused interface with only the Work method. The IHumanWorker interface extends IWorker and includes the Eat method. This way, the Robot class only implements the methods it needs, adhering to ISP.