Wednesday, September 28, 2011

PMD - Coupling Rules

The fifth installment of explanation of PMD rules covering Coupling Rules

Coupling Rules

These are rules which find instances of high or inappropriate coupling between objects and packages.

CouplingBetweenObjects

This rule counts unique attributes, local variables and return types within an object. A number higher than specified threshold can indicate a high degree of coupling.

Example

import com.Blah;
import org.Bar;
import org.Bardo;
public class Foo {
private Blah var1;
private Bar var2;
//followed by many imports of unique objects
void ObjectC doWork() {
  Bardo var55;
  ObjectA var44;
  ObjectZ var93;
  return something;
}
}

ExcessiveImports

A high number of imports can indicate a high degree of coupling within an object. Rule counts the number of unique imports and reports a violation if the count is above the user defined threshold. As the number of objects imported increases it shows an increasing level of coupling between this object and others that it has imported. We should import minimum number of objects.

Example

import blah.blah.Baz;
import blah.blah.Bif;
// 18 others from the same package elided
public class Foo {
public void doWork() {}
}

LooseCoupling

Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead. This will ensure that we can change to use a different implementation going forward. Similarly use a Map instead of a HashMap or HashTable.

Example

import java.util.*;
public class Bar {
        private ArrayList list = new ArrayList();// Use List instead
        public HashSet getFoo() { //Use Set instead
               return new HashSet();
        }
}

No comments: