logo资料库

PMD错误翻译整理.pdf

第1页 / 共40页
第2页 / 共40页
第3页 / 共40页
第4页 / 共40页
第5页 / 共40页
第6页 / 共40页
第7页 / 共40页
第8页 / 共40页
资料共40页,剩余部分请下载后查看
1.Design Rules
2.Coupling Rules
3.Finalizer Rules
4.Import Statement Rules
5.Controversial Rules
6.J2EE Rules
7.JavaBean Rules
8.Clone Implementation Rules
9.Code Size Rules
10.Junit Rules
11.Braces Rules
12.Basic Rules
13.Jakarta Commons Logging Rules
14.Java Logging Rules
15.Migration Rules
16.Naming Rules
17.Optimization Rules
18.Strict Exception Rules
19.String and StringBuffer Rules
20.Security Code Guidelines
21.Type Resolution Rules
22.Unused Code Rules
1.Design Rules · UseSingleton: If you have a class that has nothing but static methods, consider making it a Singleton. Note that this doesn't apply to abstract classes, since their subclasses may well include non-static methods. Also, if you want this class to be a Singleton, remember to add a private constructor to prevent instantiation. 翻译 使用单例:如果有一个类包含的只有静态方法,可以考虑做成单例的。注意这个 规则不适用于抽象类,因为它们的子类可能包含非静态方法。还有,如果你想把一个类 做成单例的,记得写一个私有的构造器以阻止外部实例化。 · SimplifyBooleanReturns: Avoid unnecessary if..then..else statements when returning a boolean. 翻译 简化布尔量的返回:避免在返回布尔量时写不必要的 if..then..else 表达式。 代码示例: public class Foo { private int bar =2; public boolean isBarEqualsTo(int x) { // this bit of code if (bar == x) { return true; } else { return false; } // 上面可以简化为: // return bar == x; } } SimplifyBooleanExpressions: Avoid unnecessary comparisons · expressions - this complicates simple code. 翻译 简化布尔表达式:避免布尔表达式之间无用的比较——只会使代码复杂化 代码示例: in boolean public class Bar { // 下面可以简化为: bar = isFoo(); private boolean bar = (isFoo() == true); public isFoo() { return false;} } · SwitchStmtsShouldHaveDefault: Switch statements should have a default label. 翻译 Switch 表达式应该有 default 块 · AvoidDeeplyNestedIfStmts: Deeply nested if..then statements are hard to read. 翻译 避免深度嵌套的 if 表达式:深度嵌套的 if..then 表达式难以阅读
· AvoidReassigningParameters: Reassigning values to parameters is a questionable practice. Use a temporary local variable instead. 翻译 避免给参数重新赋值:给传入方法的参数重新赋值是一种需要商榷的行为。使用 临时本地变量来代替。 · SwitchDensity: A high ratio of statements to labels in a switch statement implies that the switch statement is doing too much work. Consider moving the statements into new methods, or creating subclasses based on the switch variable. 翻译 密集的 switch:switch 表达式的 case 块中出现很高比例的表达式语句表明 switch 表达式做了太多的工作。考虑将表达式语句写进一个新的方法,或者创建基于 switch 变量的子类。 代码示例: public class Foo { public void bar(int x) { switch (x) { case 1: { // lots of statements break; } case 2: { // lots of statements break; } } } } ConstructorCallsOverridableMethod: Calling overridable methods during · construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to discern. It may leave the sub-class unable to construct its superclass or forced to replicate the construction process completely within itself, losing the ability to call super(). If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable. Note that this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls a private method bar() that calls a public method buz(), this denotes a problem. 翻译 构造器调用了可重写的方法:在构造器中调用可被覆盖的方法可能引发在一个尚 未构造完成的对象上调用方法的风险,而且是不易辨识的。它会使得子类不能构建父类 或者自己强制重复构建过程,失去调用 super()方法的能力。如果一个默认的构造器包 含一个对可重写方法的调用,子类可能完全不能被实例化。注意这也包含在整个控制流 图上的方法调用——例如:如果构造器 Foo()调用了私有方法 bar(),而 bar()又调用了 公开的方法 buz(),这就会导致问题。 代码示例: public class SeniorClass { public SeniorClass(){ toString(); //may throw NullPointerException if overridden
} public String toString(){ return "IAmSeniorClass"; } } public class JuniorClass extends SeniorClass { private String name; public JuniorClass(){ super(); //Automatic call leads to NullPointerException name = "JuniorClass"; } public String toString(){ return name.toUpperCase(); } } · AccessorClassGeneration: Instantiation by way of private constructors from outside of the constructor's class often causes the generation of an accessor. A factory method, or non-privitization of the constructor can eliminate this situation. The generated class file is actually an interface. It gives the accessing class the ability to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter. This turns a private constructor effectively into one with package scope, and is challenging to discern. 翻译 存取器类生成:从一个具有私有构建器的类的外部实例化这个类通常会导致存取 器的生成。工厂方法,或者非私有化的构造器可以避免这个情况。生成的类文件事实上 是一个接口。它赋予访问类调用一个新的隐藏的包范围的构建器并把这个接口作为补充 参数的能力。这样就把私有的构造器有效地转换为一个包范围的构建器,而且是不易觉 察的。 代码示例: public class Outer { void method(){ Inner ic = new Inner();//Causes generation of accessor class } public class Inner { private Inner(){} } } · FinalFieldCouldBeStatic: If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime. 翻译 final 类型的域可以同时是 static 的:如果一个 final 类型的域在编译时被赋值为常 量,它也可以是 static 的,那样就在每个对象运行时节省开支。 · CloseResource: Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use. 翻译 关闭资源:确保这些资源(譬如:Connection,Statement,和 ResultSet 对象)总在
使用后被关闭。 · NonStaticInitializer: A nonstatic initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing. 翻译 非静态的初始化器:非静态的初始化块将在构造器被调用的时候被访问(优先于 调用构造器)。这是一个有效的语言结构,但使用很少且易造成迷惑。 代码示例: public class MyClass { // this block gets run before any call to a constructor { System.out.println("I am about to construct myself"); } } · DefaultLabelNotLastInSwitchStmt: By convention, the default label should be the last label in a switch statement. 翻译 switch 表达式中 default 块应该在最后:按照惯例,default 标签应该是 switch 表 达式的最后一个标签。 · NonCaseLabelInSwitchStatement: A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels. 翻译 switch 表达式中没有 case 标签:在 switch 表达式中没有 case,是合法的,但 是容易造成迷惑。容易将 case 标签和非 case 标签混淆。 · OptimizableToArrayCall: A call to Collection.toArray can use the Collection's size vs an empty Array of the desired type. 翻译 优化 toArray 调用:调用 Collection.toArray 时使用集合的规模加上目标类型的空 数组作为参数。 代码示例: class Foo { void bar(Collection x) { // A bit inefficient x.toArray(new Foo[0]); // Much better; this one sizes the destination array, avoiding // a reflection call in some Collection implementations x.toArray(new Foo[x.size()]); } } · BadComparison: Avoid equality comparisons with Double.NaN - these are likely to be logic errors. 翻译 错误的比较:避免 Double.NaN 的相等性比较-这些可能是逻辑错误
· EqualsNull: Inexperienced programmers sometimes confuse comparison concepts and use equals() to compare to null. 翻译 等于空:经验缺乏的程序员有时候会迷惑于相等性概念,拿 equals()方法和 null 比较 · ConfusingTernary: In an "if" expression with an "else" clause, avoid negation in the test. For example, rephrase: if (x != y) diff(); else same(); as: if (x == y) same(); else diff(); Most "if (x != y)" cases without an "else" are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?". 翻译 令人迷惑的三种性:在 if 表达式伴随 else 子句时,避免在 if 测试中使用否定表 达。例如:不要使用 if (x != y) diff(); else same()这种表述,而应该使用 if (x == y) same(); else diff(),大多数时候使用 if(x!=y)形式时不包含 else 分句,所以一贯地使用此规则能 让代码更易于阅读。此外,这也解决了一个细节的排序问题,比如“应该是判断为 false 的代码块在前面?”,还是“判断通过的代码块在前?” · InstantiationToGetClass: Avoid instantiating an object just to call getClass() on it; use the .class public member instead. 翻译 通过 getClass 实例化:避免通过访问 getClass()实例化对象,使用.class 这个公 共属性代替。 · IdempotentOperations: Avoid idempotent operations - they are have no effect. 翻译 幂等性操作:避免幂等性操作-它们不起任何作用 幂等性操作,同样的操作无论执行多少次,其结果都跟第一次执行的结果相同。 代码示例: public class Foo { public void bar() { int x = 2; x = x; } } · SimpleDateFormatNeedsLocale: Be sure to specify a Locale when creating a new instance of SimpleDateFormat. 翻译 SimpleDateFormat 类需要本地参数:确保在创建 SimpleDateFormat 类的实例 时指定了 Locale 参数 · ImmutableField: Identifies private fields whose values never change once they are initialized either in the declaration of the field or by a constructor. This aids in converting existing classes to immutable classes. 翻译 不变域:识别出一旦被声明就赋值或通过构造器赋值后就从不改变的私有域,它 们将存在的类变成了不变类。这样的域可以是 final 的 代码示例:
public class Foo { private int x; // could be final public Foo() { x = 7; } public void foo() { int a = x + 2; } } When doing UseLocaleWithCaseConversions: · a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Turkish. 翻译 大小写转换时使用 Locale:当访问 String.toLowerCase()/toUpperCase()时使用 Locale 参数,这样可以避免某些特定的本地化问题,比如土耳其语 · AvoidProtectedFieldInFinalClass: Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead. 翻译 避免在 final 类中使用 protected 域:因为 final 类型的 class 不能被继承,所以不 要使用 protected 域,通过使用 private 或包访问符来代替以修正你的意图。 · AssignmentToNonFinalStatic: Identifies a possible unsafe usage of a static field. 翻译 给一个非 final 的 static 类型赋值:识别出一个非安全的 static 域使用 代码示例: public class StaticField { static int x; public FinalFields(int y) { x = y; // unsafe } } · MissingStaticMethodInNonInstantiatableClass: A class that has private constructors and does not have any static methods or fields cannot be used. 翻译 在不可实例化类中缺少静态方法:一个具有私有构造器且没有任何静态方法或静 态变量的类不能被使用 · AvoidSynchronizedAtMethodLevel: Method level synchronization can backfire when new code is added to the method. Block-level synchronization helps to ensure that only the code that needs synchronization gets it. 翻译 避免方法级的同步:当为一个同步的方法加入新代码时可能发生意外。块级别的 同步可以确保内含真正需要同步的代码。
· MissingBreakInSwitch: A switch statement without an enclosed break statement may be a bug. 翻译 switch 块中缺少 break:switch 表达式缺少内含的 break 块可能是 bug。 · UseNotifyAllInsteadOfNotify: Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary; thus it's usually safer to call notifyAll() instead. 翻译 使用 notifyAll 代替 notify: Thread.notify()唤醒监控对象的线程。如果多余一个线 程在监控中,只会有一个被选择。这个线程的选择是随机的,因此调用 notifyAll()代替 它更安全。 · AvoidInstanceofChecksInCatchClause: Each caught exception type should be handled in its own catch clause. 翻译 避免在 catch 块中使用 instanceof:每个产生的异常类型都应该在自己的 catch 块 中被处理。 · AbstractClassWithoutAbstractMethod: The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods. If the class is intended to be used as a base class only (not to be instantiated direcly) a protected constructor can be provided prevent direct instantiation. 翻译 抽象类没有抽象方法:抽象类没有包含抽象方法,抽象类建议未完成的方法实现, 这个方法在子类中被完成。如果类意图被用作基础类(不被直接实例化),一个 protected 的构造器就能提供对直接实例化的阻止。 · SimplifyConditional: No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument. 翻译 简化条件:在使用 instanceof 之间不需要 null 校验,当给予一个 null 作为参数时, instanceof 返回 false · CompareObjectsWithEquals: Use equals() to compare object references; avoid comparing them with ==. 翻译 对象相等性比较:使用 equals()比较对象的引用,避免使用”==”来比较 · PositionLiteralsFirstInComparisons: Position literals first in String comparisons - that way if the String is null you won't get a NullPointerException, it'll just return false. 翻译 把字面量放在比较式的前面:在字符串比较时,将字面量放在前面-这种方法能 够避免当字符串为空时的空指针异常,只是返回 false。 · UnnecessaryLocalBeforeReturn: Avoid unnecessarily creating local variables 翻译 在 return 之前不必要的本地变量:避免创建不必要的本地变量 代码示例: public class Foo { public int foo() { int x = doSomething();
return x; // instead, just 'return doSomething();' } } · NonThreadSafeSingleton: Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possible by instantiating the object directly. Static singletons are usually not needed as only a single instance exists anyway. Other possible fixes are to synchronize the entire method or to use an initialize-on-demand holder class (do not use the double-check idiom). See Effective Java, item 48. 翻译 非线程安全的单例:非线程安全的单例可以导致错误的状态转换。如果可能通过 直接实例化消除静态的单例.因为事实上只存在一个实例,所以静态单例一般是不需要 的。另外的解决办法是同步实际的方法或者使用一个按需实例化的持有类(不要使用双 重检查机制)。请参阅:Effective Java,48 章。 代码示例: private static Foo foo = null; //multiple simultaneous callers may see partially initialized objects public static Foo getFoo() { if (foo==null) foo = new Foo(); return foo; } · UncommentedEmptyMethod: Uncommented Empty Method finds instances where a method does not contain statements, but there is no comment. By explicitly commenting empty methods it is easier to distinguish between intentional (commented) and unintentional empty methods. 翻译 不含注释的空方法:不含注释的空方法就是说一个方法内部没有任何程序代码也 没有注释。通过明确的注释空方法能够容易的区分有潜在意向的和无意向的空方法。 · UncommentedEmptyConstructor: Uncommented Empty Constructor finds instances where a constructor does not contain statements, but there is no comment. By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors. 翻译 不含注释的空构造器:不含注释的空构造器就是说一个构造器内部没有任何程序 代码也没有注释。通过明确的注释空构造器能够容易的区分有潜在意向的和无意向的空 构造器 · AvoidConstantsInterface: An interface should be used only to model a behaviour of a class: using an interface as a container of constants is a poor usage pattern. 翻译 避免常量接口:接口仅仅是应该用来建模类的行为的:使用接口作为常量的容器 是一种劣质的用法。 · UnsynchronizedStaticDateFormatter: SimpleDateFormat is not synchronized. Sun recomends separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized either on method or block level.
分享到:
收藏