Interface segregation principle

Interface segregation principle states that no class should be forced to implement unneeded methods. To avoid this, we should separate methods in different interfaces so each class can implement only the needed methods.

Examples

Let's imagine we have an interface called DriveInterface, like that:

interface DriveInterface {
    public function goForward(): void;
    public function goBackwards(): void;
}

And two classes:

class Car implements DriveInterface {
    public function goForward(): void
    {
        // code goes here
    }
    public function goBackwards(): void
    {
        // code goes here
    }
}

class Motorbike implements DriveInterface {
    public function goForward(): void
    {
        // code goes here
    }
    public function goBackwards(): void
    {
        // hey wtf...
    }
}

Obviously you don't need to implement goBackwards in a motorbike, so you are being forced to implement a method you don't need.

Let's segregate this:

interface DriveForwardInterface {
    public function goForward(): void;
}

interface DriveBackwardsInterface {
    public function goBackwards(): void;
}

class Car implements DriveForwardInterface, DriveBackwardsInterface {
    public function goForward(): void
    {
        // code goes here
    }
    public function goBackwards(): void
    {
        // code goes here
    }
}

class Motorbike implements DriveForwardInterface {
    public function goForward(): void
    {
        // code goes here
    }
}

Now, motorbike don't need to implement goBackwards, and it makes sense.

Back to the glossary