DEV Community

spO0q
spO0q

Posted on

SOLID: writing better interfaces

The Interface Segregation principle (the "I" in SOLID) can be tough to understand at the beginning.

Interfaces in theory

You may declare the following interface, but it would not make sense:

interface VehiculeInterface {
    public function roll(): void;
    public function fly(): void;
}
Enter fullscreen mode Exit fullscreen mode

Why?

Because you'd have entire classes of vehicules that cannot implement all behaviors but only some of them.

It's better to write two interfaces in this case, and your vehicules may still implement both interfaces:

interface RollingVehiculeInterface {
    public function roll(): void;
}
interface FlyingVehiculeInterface {
    public function fly(): void;
}
Enter fullscreen mode Exit fullscreen mode

Interfaces in practice

Most PHP frameworks follow such principle, but you get handy feature like autowire and automatic injection, so you only have to typehint:

use Psr\Log\LoggerInterface;

class MyClass
{
    public function __construct(
        private LoggerInterface $logger,
    ) {
    }
}
Enter fullscreen mode Exit fullscreen mode

or even:

use Psr\Log\LoggerInterface;

class MyClass
{
     public function index(LoggerInterface $logger) {}
}
Enter fullscreen mode Exit fullscreen mode

What is "interface pollution"?

It's sometimes hard to resist the temptation to add methods to an existing interface.

However, it usually impacts maintenance negatively.

You can see the problem from different perspectives, but it's the same idea:

  • interfaces should not have multiple responsibilities
  • "Clients should not be forced to depend upon interfaces that they do not use" [Uncle Bob]

Why do we need that approach?

It's because interfaces allows implementing behaviors: different behaviors, different interfaces.

The ultimate goal is to prevent bad side effects, which is way easier to achieve when you split the code into simple/small/single parts.

Top comments (0)