Loose Coupling
Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead.
Here's an example of code that would trigger this rule:
import java.util.*;
public class Bar {
// Use List instead
private ArrayList list = new ArrayList();
// Use Set instead
public HashSet getFoo() {
returnnew HashSet();
}
}
Only One Return
A method should have only one exit point, and that should be the last statement in the method.
Here's an example of code that would trigger this rule:
public class OneReturnOnly1 {
public void foo(int x) {
if (x > 0) {
return "hey"; // oops, multiple exit points!
}
return "hi";
}
}
Null Assignment
Assigning a "null" to a variable (outside of its declaration) is usually bad form. Some times, the assignment is an indication that the programmer doesn't completely understand what is going on in the code.
NOTE: This sort of assignment may in rare cases be useful to encourage garbage collection. If that's what you're using it for, by all means, disregard this rule :-)
Here's an example of code that would trigger this rule:
public class Foo {
public void bar() {
Object x = null; // This is OK.
x = new Object();
// Big, complex piece of code here.
x = null; // This is BAD.
// Big, complex piece of code here.
}
}
Call Super In Constructor
It is a good practice to call super() in a constructor. If super() is not called but another constructor (such as an overloaded constructor) is called, this rule will not report it.
Here's an example of code that would trigger this rule:
public class Foo extends Bar{
public Foo() {
// call the constructor of Bar
super();
}
public Foo(int code) {
// do something with code
this();
// no problem with this
}
}
Switch Statements Should Have Default
Switch statements should have a default label.
Here's an example of code that would trigger this rule:
public class Foo {
public void bar() {
int x = 2;
switch (x) {
case 2: int j = 8;
}
}
}
Avoid Reassigning Parameters
Reassigning values to parameters is a questionable practice. Use a temporary local variable instead or use only when required.
Here's an example of code that would trigger this rule:
public class Foo {
private void foo(String bar) {
bar = "something else";
}
}
Final Field Could Be Static
If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime.
Here's an example of code that would trigger this rule:
public class Foo {
public final int BAR = 42; // this could be static and save some space
}