读书人

PMD检察代码的一些规则

发布时间: 2012-12-21 12:03:49 作者: rapoo

PMD检查代码的一些规则

?

摘抄自:http://pmd.sourceforge.net/rules/optimizations.html

一、Optimization Rules:最佳规则

1、LocalVariableCouldBeFinal:A local variable assigned only once can be declared final.

2、MethodArgumentCouldBeFinal:A method argument that is never assigned can be declared final.

3、AvoidInstantiatingObjectsInLoops:Detects when a new object is created inside a loop

public class Something {  public static void main( String as[] ) {      for (int i = 0; i < 10; i++) {      Foo f = new Foo(); //Avoid this whenever you can it's really expensive    }  }}

5、UseArrayListInsteadOfVector:ArrayList is a much better Collection implementation than Vector.

6、UseArraysAsList:The java.util.Arrays class has a "asList" method that should be used when you want to create a new List from an array of objects. It is faster than executing a loop to copy all the elements of the array one by one.

?

   public void foo(Integer[] ints) {    // could just use Arrays.asList(ints)     List l= new ArrayList(10);     for (int i=0; i< 100; i++) {      l.add(ints[i]);     }     for (int i=0; i< 100; i++) {      l.add(a[i].toString()); // won't trigger the rule     }    }

?

?7、AvoidArrayLoops:Instead of copying data between two arrays, use?System.arraycopy?method.

?

public void bar() {  int[] a = new int[10];  int[] b = new int[10];  for (int i=0;i<10;i++) {   b[i]=a[i];  } }// this will trigger the rule   for (int i=0;i<10;i++) {      b[i]=a[c[i]];    }}     

8?、AddEmptyStirng:Finds empty string literals which are being added. This is an inefficient(无效) way to convert any type to a String.

?

?

 String s = "" + 123; // bad  String t = Integer.toString(456); // ok 


二、Basic Rules:The Basic Ruleset contains a collection of good practices which everyone should follow.1、EmptyCatchBlock:
public void doSomething() {  try {    FileInputStream fis = new FileInputStream("/tmp/bugger");  } catch (IOException ioe) {      // not good  }
2、JumbledIncrementer:Avoid jumbled loop incrementers - it's usually a mistake, and it's confusing even if it's what's intended.
for (int i = 0; i < 10; i++) {    for (int k = 0; k < 20; i++) {     System.out.println("Hello");    }}
?3、UnnecessaryConventionTemporary:Avoid unnecessary temporaries when converting primitives to Strings
// this wastes an object  String foo = new Integer(x).toString();// this is better  return Integer.toString(x);
??3、DoubleCheckingLocking:Partially(部分的) created objects can be returned by the Double Checked Locking pattern when used in Java. An optimizing(最佳的) JRE may assign a reference to the baz variable before it creates the object the reference is intended to point to
 Object baz;  Object bar() {    if(baz == null) { //baz may be non-null yet not fully created      synchronized(this){        if(baz == null){          baz = new Object();        }      }    }    return baz;  }
?4、ReturnFromFinalBlock:Avoid returning from a finally block - this can discard exceptions.?5、UnnecessaryReturn
 public void bar() {  int x = 42;  return; }
6、UnnecessaryReturn7、UnConditionIfStatement:Do not use "if" statements that are always true or always false.8、BooleanInstantiation:Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf() instead.9、UnnnessaryFinalModifier:
public final class Foo {    // This final modifier is not necessary, since the class is final    // and thus, all methods are final    private final void foo() {    }}
?10、CollapsiableIfStament:Sometimes two 'if' statements can be consolidated(合并) by separating their conditions with a boolean short-circuit operator(短路&&).
void bar() {  if (x) {   if (y) {    // do stuff   }  } }
11、ClassCastExceptionWithToArray:
public static void main(String[] args) {        Collection c=new ArrayList();        Integer obj=new Integer(1);        c.add(obj);        // this would trigger the rule (and throw a ClassCastException if executed)        Integer[] a=(Integer [])c.toArray();        // this wouldn't trigger the rule        Integer[] b=(Integer [])c.toArray(new Integer[c.size()]);    }
12、BrokenNullCheck:The null check is broken since it will throw a NullPointerException itself. It is likely that you used || instead of && or vice versa(反之亦然).
// should be &&  if (string!=null || !string.equals(""))    return string;  // should be ||  if (string==null && string.equals(""))    return string;
?13、AvoidUsingOctalValue:Integer literals should not start with zero. Zero means that the rest of literal will be interpreted(理解) as an octal value(八进制).
public class Foo {     int i = 012; // set i with 10 not 12     int j = 010; // set j with 8 not 10     k = i * j; // set k with 80 not 120}
?







读书人网 >编程

热点推荐