Sobes.tech
Middle

What is the difference between coupling and cohesion in programming?

sobes.tech AI

Answer from AI

  • Coupling: Measures the degree of dependency between modules. Low coupling is preferable because changes in one module have less impact on others. High coupling makes understanding, testing, and reusing code more difficult.
  • Cohesion: Measures the extent to which elements (functions, classes) within a module are logically related and work towards a single task. High cohesion is preferable as it makes the module more focused, understandable, and maintainable.

Example in PHP:

Low cohesion (class performs unrelated tasks):

<?php
class MixedOperations {
    public function saveUser($user) {
        // User saving logic
    }

    public function sendEmail($email, $subject, $body) {
        // Email sending logic
    }

    public function calculateDiscount($price) {
        // Discount calculation logic
    }
}

High cohesion (class focused on one task):

<?php
class EmailService {
    public function sendEmail($email, $subject, $body) {
        // Email sending logic
    }

    public function formatEmailBody($data) {
        // Email body formatting logic
    }
}

High coupling (two classes are tightly linked):

<?php
class OrderProcessor {
    private $databaseConnection;

    public function __construct($connection) {
        $this->databaseConnection = $connection; // Tight dependency on a specific connection
    }

    public function processOrder($order) {
        $this->databaseConnection->query("..."); // Direct use of external component
    }
}

class DatabaseConnection {
    public function query($sql) {
        // Query execution logic
    }
}

Low coupling (using interface for dependency inversion):

<?php
interface DatabaseInterface {
    public function query($sql);
}

class OrderProcessor {
    private $database;

    public function __construct(DatabaseInterface $database) { // Dependency on abstraction
        $this->database = $database;
    }

    public function processOrder($order) {
        $this->database->query("..."); // Using abstraction
    }
}

class MySqlDatabase implements DatabaseInterface {
    public function query($sql) {
        // MySQL implementation
    }
}

Comparison table:

Characteristic Coupling Cohesion
Measures Dependency between modules Internal consistency of a module
Goal Reduction Increase
Ideal state Low High
Impact on code Understanding, testing, response to changes Clarity, maintainability, readability
What is the difference between coupling and cohesion… - sobes.tech