PMD规则之Basic Rules

18 篇文章 1 订阅

·   EmptyCatchBlock: Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this swallows an exception which should either be acted on or reported.

翻译   空的 catch 块:发现空的 catch 块没做任何异常处理的事,在大多数情形下,这会吞噬一些应该被处理或报告的异常

·   EmptyIfStmt: Empty If Statement finds instances where a condition is checked but nothing is done about it.

翻译   空的 if 表达式:发现使用 if 进行了条件判断,但是判断之后没做任何处理

·   EmptyWhileStmt: Empty While Statement finds all instances where a while statement does nothing. If it is a timing loop, then you should use Thread.sleep() for it; if it's a while loop that does a lot in the exit expression, rewrite it to make it clearer.

翻译   空的 while 表达式:发现空的 while 表达式,如果是一个定时的循环,你应该在循环体内使用 Thread.sleep() ;如果是对于退出处理做的一个处理大量事情的 while 循环,重写代码使它更清晰

·   EmptyTryBlock: Avoid empty try blocks - what's the point?

翻译 空的 try 块:避免空的 try

·   EmptyFinallyBlock: Avoid empty finally blocks - these can be deleted.

翻译 空的 finally 块:避免空的 finally - 这些是可以删掉的

·   EmptySwitchStatements: Avoid empty switch statements.

翻译 空的 switch 表达式:避免空的 switch 表达式

·   JumbledIncrementer: Avoid jumbled loop incrementers - it's usually a mistake, and it's confusing even if it's what's intended.

翻译 避免混乱的循环 增量 - 它常常是一个错误,而且容易让人迷惑

错误代码示例:

public class JumbledIncrementerRule1 {

  public void foo() {

   for (int i = 0; i < 10; i++) {

    for (int k = 0; k < 20; i++) {

     System.out.println("Hello");

    }

   }

  }

  }

父子循环都用i++

·   ForLoopShouldBeWhileLoop: Some for loops can be simplified to while loops - this makes them more concise.

翻译 有些 for 循环可以简化为 while 循环 - 这样可以更加简明

代码示例:

public class Foo {

  void bar() {

  for (;true;) true; // 没有初始化块和变化块,相当于 : while (true)

  }

}

·   UnnecessaryConversionTemporary: Avoid unnecessary temporaries when converting primitives to Strings

翻译   将原始类型转换为字符串类型时不必要的临时转换

代码示例:

public String convert(int x) {

  // 多了一个创建对象环节

  String foo = new Integer(x).toString();

  // 下面这种写法就好了

  return Integer.toString(x);

}

·   OverrideBothEqualsAndHashcode: Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass.

翻译   同时重写 equals() hashCode() 方法:要么全部重写这两个方法,要么全部不重写

·   DoubleCheckedLocking: 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. For more details see http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html.

翻译   双重检查锁机制:在 JAVA 中有时候创建的对象是通过双重检查机制获取的,一个优化的 JRE 可能在真正创建对象之前先将指向这个对象的引用赋给一个变量,如 baz, 需要更多细节参考: http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html .

示例代码:

public class Foo {

  Object baz;

Object bar() {

/** 这里当对象没创建完时也可能判断不为空,那么在多线程环境下,就可能导致某些线程使用 bar() 方法后直接返回一个未指向完整对象的 baz 引用,从而发生错误,也可以参考笔者博客: http://blog.csdn.net/jack0511/archive/2009/02/04/3862382.aspx   */

     if(baz == null) {

      synchronized(this){

        if(baz == null){

          baz = new Object();

        }

      }

     }

    return baz;

  }

}

·   ReturnFromFinallyBlock: Avoid returning from a finally block - this can discard exceptions.

翻译   finally 块中返回:避免从 finally 块中返回 - 这会导致异常捕获后又被抛弃 .

public class Bar {

  public String foo() {

  try {

   throw new Exception( "My Exception" );

  } catch (Exception e) {

   throw e;

  } finally {

   return "A. O. K."; //. 这句导致 catch 到的异常直接被丢弃,强制返回“ A.O.K

  }

  }

}

·   EmptySynchronizedBlock: Avoid empty synchronized blocks - they're useless.

翻译   空的 Synchronized 块:避免空的 synchronized - 它们是无用的

·   UnnecessaryReturn: Avoid unnecessary return statements

翻译   不必要的 Return :避免不必要的 return 语句

示例代码:

public class Foo {

  public void bar() {

  int x = 42;

  return;

  }

}

 

·   EmptyStaticInitializer: An empty static initializer was found.

翻译   空的静态初始化块:发现一个空的静态初始化块

示例代码:

public class Foo {

  static {

  // empty

  }

}

·   UnconditionalIfStatement: Do not use "if" statements that are always true or always false.

翻译   非条件化的 if 表达式 : 当表达式总是为真或总为假时,不要用 if

public class Foo {

  public void close() {

  if (true) {

       // ...

   }

  }

}

·   EmptyStatementNotInLoop: An empty statement (aka a semicolon by itself) that is not used as the sole body of a for loop or while loop is probably a bug. It could also be a double semicolon, which is useless and should be removed.

翻译   非循环中不要有空的表达式:在一个非 for 循环或非 while 循环体中使用的一个空的表达式(或者称为一个分号)可能是一个 bug 。也可能是一对分号,这是无用的需要被移除的

代码示例:

public class MyClass {

   public void doit() {

      // 下面只用了一个;号

      ;

      // 语句结尾用了两个;号

      System.out.println("look at the extra semicolon");;

   }

}

·   BooleanInstantiation: Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf() instead.

翻译   布尔量实例化:避免实例化一个布尔对象;用指向 Boolean.TRUE,Boolean.FALSE Boolean.valueOf() 的引用代替

·   UnnecessaryFinalModifier: When a class has the final modifier, all the methods are automatically final.

翻译   非必要的 final 修饰符:注意当一个类被 fianl 修饰时,所有这个类的方法就自动变为 final 类型了

·   CollapsibleIfStatements: Sometimes two 'if' statements can be consolidated by separating their conditions with a boolean short-circuit operator.

翻译   分解的 if 表达式:有时候两个 if 语句可以通过布尔短路操作符分隔条件表达式组合成一条语句

·   UselessOverridingMethod: The overriding method merely calls the same method defined in a superclass

翻译   无用的方法重写:重载的方法仅仅调用了父类中定义的同名方法

·   ClassCastExceptionWithToArray: if you need to get an array of a class from your Collection, you should pass an array of the desidered class as the parameter of the toArray method. Otherwise you will get a ClassCastException.

翻译   toArray 时类型转换异常:如果你想从一个枚举类型中得到某个类型的数组,你应该传给 toArray() 方法一个目的类型的数组作为参数,否则你可能得到一个类型转换错误

·   AvoidDecimalLiteralsInBigDecimalConstructor: One might assume that "new BigDecimal(.1)" is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances notwithstanding. The (String) constructor, on the other hand, is perfectly predictable: 'new BigDecimal(".1")' is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.

翻译   避免在 BigDecimal 类型的构造方法中用小数类型的字面量:人们常常以为 ”new BigDecimal(0.1)” 能精确等于 0.1, 其实不然,它等于“ 0. 1000000000000000055511151231257827021181583404541015625 ”,这种状况的原因是 0.1 不能精确的表示双精度类型,因此,传入构造器的 long 类型不等于 0.1 ,而传入 String 类型的构造器 new BigDecimal(“0.1”) 可以精确等于 0.1, 故推荐这种情形时用 String 类型的构造器

·   UselessOperationOnImmutable: An operation on an Immutable object (String, BigDecimal or BigInteger) won't change the object itself. The result of the operation is a new object. Therefore, ignoring the operation result is an error.

翻译   对于不变类型的无用操作:对于不变类型对象 (String,BigDecimal BigInteger) 的操作不会改变对象本身,但操作结果是产生新的对象,所以,忽略操作的结果是错的

示例代码:

import java.math.*;

class Test {

  void method1() {

  BigDecimal bd=new BigDecimal(10);

  bd.add(new BigDecimal(5)); // 这里违背了规则

  }

  void method2() {

  BigDecimal bd=new BigDecimal(10);

  bd = bd.add(new BigDecimal(5)); // 这里没有违背规则

  }

}

·   MisplacedNullCheck: The null check here is misplaced. if the variable is null you'll get a NullPointerException. Either the check is useless (the variable will never be "null") or it's incorrect.

翻译   错位的空检查:这里的空检查是放错位置的。如果变量为空你将得到一个空指针异常。可能因为检查是无用的或者是不正确的

public class Foo {

  void bar() {

  if (a.equals(baz) && a != null) {}

  }

}

 

public class Foo {

  void bar() {

  if (a.equals(baz) || a == null) {}

  }

}

·   UnusedNullCheckInEquals: After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object's equals() method.

翻译   使用 equals() 时无用的空检查:在对一个对象引用进行完空检查后,你应该在这个对象上调用 equals() 方法而不是将它传给另一个对象的 equals() 方法作为参数

·   AvoidThreadGroup: Avoid using ThreadGroup; although it is intended to be used in a threaded environment it contains methods that are not thread safe.

翻译   避免线程组:避免使用线程组;虽然线程组可以被用于多线程环境中,但它包含的方法不是线程安全的

public class Bar {

     void buz() {

      ThreadGroup tg = new ThreadGroup("My threadgroup") ;

      tg = new ThreadGroup(tg, "my thread group");

      tg = Thread.currentThread().getThreadGroup();

      tg = System.getSecurityManager().getThreadGroup();

     }

    }

·   BrokenNullCheck: The null check is broken since it will throw a NullPointerException itself. It is likely that you used || instead of && or vice versa.

翻译   破坏空检查:如果自身抛出空指针异常空检查就会遭到破坏,比如你使用 || 代替 && ,反之亦然。

class Foo {

  String bar(String string) {

  // 这里应该是 &&

  if (string!=null || !string.equals(""))

    return string;

  // 这里应该是 ||

  if (string==null && string.equals(""))

    return string;

  }

}

·   BigIntegerInstantiation: Don't create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) and for 1.5 on, BigInteger.TEN and BigDecimal (BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN)

翻译   BigInteger 实例化:不要创建已经存在的 BigInteger 类型的实例,(如 BigInteger.ZERO,BigInteger.ONE , 对于 JDK.1.5 以上, BigInteger.TEN BigDecimal (BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN)

public class Test {

 

  public static void main(String[] args) {

   BigInteger bi=new BigInteger(1);

   BigInteger bi2=new BigInteger("0");

   BigInteger bi3=new BigInteger(0.0);

   BigInteger bi4;

   bi4=new BigInteger(0);

  }

}

·   AvoidUsingOctalValues: Integer literals should not start with zero. Zero means that the rest of literal will be interpreted as an octal value.

翻译   避免使用八进制值:整型字面量不要以 0 开头, 0 意味着之后的值要被解释为一个八进制值。

·   AvoidUsingHardCodedIP: An application with hard coded IP may become impossible to deploy in some case. It never hurts to externalize IP adresses.

翻译   避免使用 IP 硬编码:一个应用中的硬编码 IP 将使系统在某些情况下无法发布

·   CheckResultSet: Always check the return of one of the navigation method (next,previous,first,last) of a ResultSet. Indeed, if the value return is 'false', the developer should deal with it !

翻译   检查 ResultSet :总是需要检查 ResultSet 对象的导航方法( next,previous,first,last )的返回 , 事实上,如果返回 false ,开发者需要处理它
// This is NOT appropriate !

            Statement stat = conn.createStatement();

            ResultSet rst = stat.executeQuery("SELECT name FROM person");

            rst.next(); // what if it returns a 'false' ?

            String firstName = rst.getString(1);

 

            // This is appropriate...

            Statement stat = conn.createStatement();

             ResultSet rst = stat.executeQuery("SELECT name FROM person");

            if (rst.next())

            {

                String firstName = rst.getString(1);

            }

            else

            {

                // here you deal with the error ( at least log it)

            }

·   AvoidMultipleUnaryOperators: Using multiple unary operators may be a bug, and/or is confusing. Check the usage is not a bug, or consider simplifying the expression.

翻译   避免使用多重的一元运算符:使用多重的一元运算符可能是一个 bug ,并且可能令人迷惑。检查确保你的用法不是一个 bug ,或者考虑简化表达

// These are typo bugs, or at best needlessly complex and confusing:

            int i = - -1;

            int j = + - +1;

            int z = ~~2;

            boolean b = !!true;

            boolean c = !!!true;

 

            // These are better:

            int i = 1;

            int j = -1;

            int z = 2;

            boolean b = true;

            boolean c = false;

 

            // And these just make your brain hurt:

            int i = ~-2;

            int j = -~7;

·   EmptyInitializer: An empty initializer was found.

翻译   空的初始化块:发现空的初始化块

public class Foo {

 

   static {} // Why ?

 

   {} // Again, why ?

 

}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值