Sobes.tech
Middle

What is cohesion and coupling in programming?

sobes.tech AI

Answer from AI

Cohesion is a measure of how closely related the elements within a module (class, function) are. High cohesion means that the elements of a module are focused on performing a single task or concept. A well-designed module has high cohesion.

Examples of cohesion levels (from low to high):

  • Coincidental: Elements are related randomly, with no logical connection.
  • Logical: Elements perform a set of logically related actions, but the choice is made by external code.
  • Temporal: Elements are related by being executed at the same time.
  • Procedural: Elements follow a procedure for execution.
  • Communicational: Elements work with the same data.
  • Sequential: The output of one element is the input for another.
  • Functional: All elements contribute to performing a single, well-defined function.

Coupling is a measure of dependency between different modules. Low coupling means modules are relatively independent of each other. Reducing coupling makes the system more flexible, maintainable, and testable.

Examples of coupling levels (from high to low):

  • Content: One module directly accesses the internal data or implementation of another module.
  • Common: Modules use a shared global data area.
  • Control: One module passes a control flag that determines the behavior of another module.
  • Stamp: Transfer of composite data (objects, structures), but the module uses only part of it.
  • Data: Transfer of simple data as parameters.
  • Message: Modules exchange messages (e.g., via events, interfaces). This is the weakest form of coupling.

The goal of good design: high cohesion (within modules) and low coupling (between modules).

<?php

// Example of high cohesion (Functional Cohesion)
// This class is focused only on user processing
class UserManager {
    private array $users = [];

    public function addUser(string $name): void {
        $this->users[] = $name;
    }

    public function getUsers(): array {
        return $this->users;
    }

    public function deleteUser(string $name): void {
        $this->users = array_filter($this->users, fn($user) => $user !== $name);
    }
}

// Example of low coupling (Data Coupling)
// 'processOrder' depends only on the data passed ($orderId, $amount)
class OrderProcessor {
    public function processOrder(int $orderId, float $amount): bool {
        // Order processing logic...
        // Does not depend directly on other classes' implementation,
        // only on input data.
        echo "Processing order ID $orderId with amount $amount\n";
        return true;
    }
}

// Example where UserManager and OrderProcessor do not have a strong dependency on each other.
// They can be used independently or together, but their internal changes
// do not significantly affect each other.

?>
What is cohesion and coupling in programming? — PHP - sobes.tech