Chidamber & Kemerer provide a metric for measuring a module's lack of cohesion (LCOM1). There are several minor improvements on this metric (LCOM2 and LCOM3).
The basic idea is to measure how far a class is from information cohesion by measuring the degree to which the methods share the fields.
In a method coupling graph for a class C-- MCG(C)-- nodes are methods. Two nodes are connected by an undirected edge if they both reference the same field. In fact, the edge can be labeled by the number of common attributes the methods reference.
(a) Draw MCG(Test) where Test is the following class:
class Test {
int a, x, y, z;
void m1() {
System.out.println(x);
System.out.println(y);
}
void m2() {
System.out.println(y);
System.out.println(z);
}
void m3() {
System.out.println(x);
System.out.println(z);
}
void m4() {
System.out.println(a);
}
void m5() {
System.out.println(a);
}
}
LCOM1(C) is the maximum possible number of edges in MGC(C) less the actual number of edges:
LCOM1(C) = choose(n, 2) - e
where:
n = # of nodes in MCG(C) = # of methods in C
choose(n, 2) = n * (n - 1) / 2 = maximum # of possible edges
e = # of edges in MCG(C)
(b) Compute LCOM1(Test).
(c) Assume a class C has 10 methods. What are the possible values of LCOM1(C)?
(d) Under what conditions does LCOM1(C) = 0?
In a method-attribute graph for a class C-- MAG(C)-- nodes are methods and attributes (fields). A directed edge connects a method node to an attribute node if the method references the attribute.
(e) Draw MAG(Test).
If every method of class C references every field of C, then MAG(C) would contain n*a edges, where:
n = # of methods
a = # of attributes
Assume:
e = # of edges in MAG(C)
Then e/(n*a) measures C's degree of cohesion. Since this number is <= 1, then 1 minus this number measures C's lack of cohesion:
LCOM2(C) = 1 - e/(n * a)
(f) Compute LCOM2(Test).
Finally:
LCOM3(C) = n/(n - 1) * LCOM2(C) = (n - e/a)/(n - 1)
(g) Compute LCOM3(Test).
(h) Prove 0 <= LCOM2(C) <= 1
(i) Prove 0 <= LCOM3(C) <= 2
(j) What action would you recommend if LCOM3(C) > 1?