Sobes.tech
Middle

On what principle are methods in interfaces combined and separated?

sobes.tech AI

Answer from AI

Methods in interfaces are grouped and separated based on the principle of cohesion of behavior and the principle of explicit contract.

  • Cohesion of behavior: Methods that represent a single set of operations on an entity or perform similar actions are grouped into one interface. This improves code readability, makes the purpose of the interface clearer, and increases its reusability.
  • Explicit contract: The interface describes an explicit contract that implementing classes must fulfill. Each method in the interface is part of this contract. Methods are separated into different interfaces if they represent different aspects of behavior or if their implementation can vary independently. For example, an Readable interface might contain methods for reading data, while a Writable interface might contain methods for writing. A class can implement one or both of these interfaces depending on its capabilities.

This approach supports SOLID principles, in particular:

  • Single Responsibility Principle: The interface has one reason to change — a change in the set of behaviors it describes.
  • Interface Segregation Principle: Clients should not depend on interfaces they do not use. Splitting large interfaces into smaller, focused ones allows classes to implement only the interfaces they actually need.

Example:

Suppose we have an entity that can be saved and loaded. Instead of a single Persistable interface with two methods save() and load(), it is better to create two separate interfaces:

// Interface for entities that can be saved
interface Savable
{
    public function save(): void;
}
// Interface for entities that can be loaded
interface Loadable
{
    public function load(): void;
}

A class that can both be saved and loaded implements both interfaces:

// Class implementing both interfaces
class DataObject implements Savable, Loadable
{
    public function save(): void
    {
        // Saving logic
    }

    public function load(): void
    {
        // Loading logic
    }
}

A class that only needs to be saved implements only Savable:

// Class implementing only the Savable interface
class TempData implements Savable
{
    public function save(): void
    {
        // Saving temporary data logic
    }
}

This allows for more flexible class design and dependencies.