Sobes.tech
Middle

What is strong and weak coupling in the context of programming and understanding code?

sobes.tech AI

Answer from AI

Tight coupling:

  • Modules depend heavily on each other.
  • Changing one module often requires changes in others.
  • Makes testing and reuse more difficult.
  • Example: Direct method calls between classes without interfaces.

Loose coupling:

  • Modules depend less on each other.
  • Changes in one module have less impact on others.
  • Simplifies testing, reuse, and maintenance.
  • Example: Using interfaces, Dependency Injection, messaging.

Example of tight coupling:

// package com.example.tightcoupling;

class OrderProcessor {
    private PaymentGateway paymentGateway = new PaymentGateway(); // Direct dependency

    public void processOrder(Order order) {
        // Order processing logic
        paymentGateway.chargeCard(order.getTotal()); // Direct method call
        // ...
    }
}

class PaymentGateway {
    public void chargeCard(double amount) {
        // Payment logic
    }
}

Example of loose coupling:

// package com.example.loosecoupling;

interface PaymentGateway {
    void chargeCard(double amount);
}

class CreditCardPaymentGateway implements PaymentGateway {
    @Override
    public void chargeCard(double amount) {
        // Credit card payment logic
    }
}

class PayPalPaymentGateway implements PaymentGateway {
    @Override
    public void chargeCard(double amount) {
        // PayPal payment logic
    }
}

class OrderProcessor {
    private PaymentGateway paymentGateway; // Dependency on interface

    public OrderProcessor(PaymentGateway paymentGateway) { // Dependency injection
        this.paymentGateway = paymentGateway;
    }

    public void processOrder(Order order) {
        // Order processing logic
        paymentGateway.chargeCard(order.getTotal()); // Call via interface
    }
}

Difference in understanding code:

Characteristic Tight coupling Loose coupling
Flow understanding Easier to trace direct calls between classes Requires understanding abstractions (interfaces)
Isolation for testing Harder to test in isolation Easier to test individual modules
Impact of changes Changes often require understanding others Changes less likely to affect others
Testing Harder to write unit tests for modules Easier to write unit tests for modules