Keep interfaces small so that users don’t end up depending on things they don’t need..

What is SOLID?

This is a series on the basics of the SOLID principles of software engineering. The SOLID principles were created by Robert C. Martin “Uncle Bob” who is a software engineer public speaker and author.

SOLID is an acrostic that stands for:

There will be an article for each. Lets take a look at Interface Segregation Principle.

Interface Segregation Principle

Non Compliant Example

interface IBusinessBehavior
{
    int RunRules();

    int RunMoreRules();
}

class MyBusinessBehavior : IBusinessBehavior
{
    public int RunRules()
    {
        return 1;
    }

    public int RunMoreRules()
    {
        return 2;
    }
}

class MyNewBusinessBehavior : IBusinessBehavior
{
    public int RunRules()
    {
        return 3;
    }

    public int RunMoreRules()
    {
        throw new NotImplementedException();
    }
}

You can see here if someone injects the MyNewBusinessBehavior as the IBusinessBehavior, then a class that uses this as a dependency will call the RunMoreRules and get an exception at run time.

The real problem here is the interface has not been defined properly. Consider the following:

Compliant Example

interface IBusinessBehavior
{
    int RunRules();

}

interface IMoreRulesBusinessBehavior
{
    int RunMoreRules();
}

class MyBusinessBehavior : IBusinessBehavior, IMoreRulesBusinessBehavior
{
    public int RunRules()
    {
        return 1;
    }

    public int RunMoreRules()
    {
        return 2;
    }
}

class MyNewBusinessBehavior : IBusinessBehavior
{
    public int RunRules()
    {
        return 3;
    }

}

In this example the interface has been better defined, anyone that depends on the IBusinessBehavior gets either MyBusinessBehavior or MyNewBusinessBehavior what ever you have defined in your DI, and anyone just depending on the IMoreRulesBusinessBehavior will get MyBusinessBehavior and you will not have a runtime error.

Conclusion

In the real world I see this principle violated all the time. Typically if you are working with a microsoft framework for instance and you don’t know what you need to do to implement some method in the abstract it means you do not completely understand what you are trying to do.

Here is a bit of Robert Martin’s recent take on the validity of this principle in 2020: