DEV Community

spO0q
spO0q

Posted on

Interfaces or abstract classes?

Working with objects can be tough sometimes, especially when you don't know which structure you need to use.

For example, both abstract classes and interfaces can force other classes to implement some methods.

Interfaces are "contracts"

Classes that implement an interface must implement its methods.

For example, you can ensure classes that aim to log data have the appropriate methods and behaviors.

This way, you can safely use some methods in your code, as the class implements the interface that defines the desired behavior.

Whether the term "contract" is the best one to describe interfaces is another debate.

The problem here is to know when you should probably use an interface instead of an abstract class, and vice versa.

Method signatures only?

Both interfaces and abstract classes can contain method signatures that must be implemented by classes that use them.

interface LoggingInterface
{
    public function warning($message, array $context = array()): void;
}

abstract class Logging
{
    abstract public function warning($message, array $context = array()): void;
}
Enter fullscreen mode Exit fullscreen mode

Both structures cannot be instantiated and must be implemented (interfaces) or extended (abstract classes). However, interfaces cannot have properties and functionalities (~ methods with a body).

What's the difference, then?

PHP classes can implement several interfaces, but it's not possible to extend multiple classes.

IMHO, this is the key to understand when you should use interfaces or abstract classes.

If you need to pass some functionalities (not abstract) and properties to a group of classes, abstract classes can be beneficial. If you only want to ensure your classes will implement a specific behavior, use interfaces.

In our example above, an interface seems more appropriate, and it's not just to ensure the warning() method will be implemented with a specific signature.

Use both structures to improve your code

Whether you use interfaces or abstract classes, it's usually a better approach than classic extends or big switch cases.

The code should also be more readable, as you can cut lots of if conditions and prevent unnecessary repetitions.

Of course, it's still possible to write bad code, but these structures can help you find your way.

Interfaces and abstract classes are very similar, but an abstract class is like a base code for your objects that can provide default implementation, so the classes that extend them are usually related.

In contrast, interfaces focus on behaviors and can group unrelated classes.

Top comments (0)