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.
LCOM4 looks at your class and counts how many “Islands” of code you have.
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.
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.
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.”
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!”