scitools.com

← Metric catalog

Percent Lack Of Cohesion is one of the source-code metrics Understand computes across 17+ languages — browse them in the GUI, export and track them, or script them with the Python API.

Percent Lack Of Cohesion

API ID: PercentLackOfCohesion
Also Known As: LCOM2, Lack of Cohesion in Methods (LCOM/LOCM)
Languages: Ada, Basic, C#, C++, Java, Pascal
Targets: Classes, Packages

100% minus the average cohesion for class data members, or for package entities, 100% minus the average cohesion of the packaged classes.

For a class, this calculates what percentage of (data member, method) pairs actually interact: for every data member (instance or static) and every local, non-implicit method (instance or static), the pair counts if the method reads, writes, calls, or otherwise modifies that member. The percentage of pairs that interact, out of all possible pairs, is the class's cohesion; subtracting that from 100% gives the lack of cohesion. A lower percentage means higher cohesion between class data and methods.

For example:


class CohesionClass {
public:
  void func1() {
    for (int i = 0; i < mVar1; i++) {
      mVar2 = nullptr;
    }
    mVar1 = 3;
  }

  void func2() {
    mVar1 = 4;
  }

  static void addObj() {
    sNumObjs ++;
  }
protected:

  void func3() {
    mVar2 = "blue";
  }
private:

  void func4() {

  }

  int mVar1;
  char * mVar2;
  static int sNumObjs;
};

int CohesionClass::sNumObjs = 3;

CohesionClass has 3 data members (mVar1, mVar2, sNumObjs) and 5 local methods (func1, func2, func3, func4, addObj), for 3 × 5 = 15 possible pairs. mVar1 is touched by func1 (read in the for-loop condition, then written) and func2 (written): 2 methods. mVar2 is touched by func1 and func3: 2 methods. sNumObjs is touched by addObj: 1 method. func4 touches nothing. That's 2 + 2 + 1 = 5 interacting pairs out of 15 possible, or 33% cohesion, so PercentLackOfCohesion = 100% - 33% = 67.

See Percent Lack Of Cohesion Modified to avoid penalizing methods that touch data only through the class's own accessor methods.

Also known as Chidamber & Kemerer - Lack of Cohesion in Methods (LCOM/LOCM); LCOM2.


Targets By Language: Configuration: