phanalist

E0015: The “Islands of Code” Rule (LCOM4)

Imagine a class is like a room in your house. Cohesion is a fancy word for “how much everything in this room belongs together.”

If you put a toilet in your kitchen, the room has “low cohesion.” It’s doing two totally different things that don’t touch each other.

How the rule works

LCOM4 looks at your class and counts how many “Islands” of code you have.

  1. If Method A uses Property X, they are on the same island.
  2. If Method B uses Property Y, they are on another island.
  3. If Method A and Method B never talk to each other, and they don’t share any properties, you have 2 Islands.

In a good class, the score should always be 1. If your score is 2 or higher, it means you have two different “islands” of logic living in the same class that don’t actually need each other.


❌ The “Low Cohesion” Example (Score: 2)

This class is like a “Kitchen-Bathroom.” It’s messy because it handles two different jobs.

class UserManager {
    private $db;
    private $logger;

    // ISLAND 1: Dealing with the database
    public function saveUser($user) {
        $this->db->save($user);
    }

    // ISLAND 2: Dealing with log files
    // This doesn't use $db, and saveUser() doesn't use this!
    public function logError($message) {
        $this->logger->write($message);
    }
}

The fix: Split this into UserRepository and ErrorLogger.


✅ The “High Cohesion” Example (Score: 1)

Everything here is working together on the same island.

class Counter {
    private $count = 0;

    public function increment() {
        $this->count++; // Uses $count
    }

    public function getCount() {
        return $this->count; // Also uses $count
    }
}

Why it’s good: Both methods use the same variable. They are “connected.”


The Junior’s Rule of Thumb:

If Phanalist tells you your LCOM4 score is high, it’s basically saying: “Hey! You’ve got two different classes hiding inside this one file. Give them their own homes!”