Powered by CodePro and Eclipse
Severity: Low
Summary
The compareTo method is expected to throw ClassCastException and NullPointerException.
Description
It is not necessary to test the value of the argument to compareTo prior to casting it. If the argument is null a NullPointerException should be thrown. If it is of the wrong type a ClassCastException should be thrown.
Notes
See the item in Effective Java titled "Consider implementing Comparable" for a full discussion of the do's and don'ts of the compareTo method.
Severity: Medium
Summary
Every class should override toString().
Description
This audit rule identifies non-abstract classes that do not override the toString method.
Notes
Effective Java makes three important points about the toString method. 1. Providing a good toString implementation makes your class much more pleasant to use. 2. The toString method should return all the interesting information contained in the object. 3. The object should provide programmatic access to all the information presented by toString.
Severity: Medium
Summary
Avoid finalizers.
Description
Finalizers should be avoided because they can lead to obscure bugs and apparent consumption of operating system resources.
Example
Any method with the signature "finalize()" will be flagged.
Notes
To quote from Effective Java: "Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. Finalizers have a few valid uses, ... but as a rule of thumb, finalizers should be avoided."
Severity: Medium
Summary
It is best to avoid creating subtypes of Cloneable.
Description
The Cloneable interface serves no purpose other than to modify the behavior of Object's clone method. There's no reason for interfaces to extend it. Classes rarely benefit from implementing it; there are better ways to copy objects than by cloning.
Notes
The Cloneable interface implements an extra-linguistic device that did not live up to expectations, according to Effective Java. There are better ways to copy objects than by using the clone method.
Severity: Medium
Summary
Boolean method names should start with 'is', 'can', 'has' or 'have'. Non-boolean methods should not start with 'is'.
Description
This audit rule checks the names of all boolean methods to make sure that they are prefixed with 'is', 'can', 'has' or 'have'. It also checks the names of all non-boolean methods to make sure that they are not prefixed with 'is'.
Example
The following method would be flagged as a violation because it returns a boolean value but does not start with an approved prefix:
public boolean willExplodeIfShaken()
The following method would be flagged as a violation because it starts with 'is' but does not return a boolean:
public int isRoundedBy()
Severity: Medium
Summary
Class names should conform to the defined standard.
Description
This audit rule checks the names of all classes.
Example
If class names are specified as needing to start with an uppercase letter, the following class definition would be flagged as being a violation:
public class remoteDatabase { ... }
Severity: Medium
Summary
Type names should end with "Exception" if, and only if, they are derived from java.lang.Exception. Similarly, type names should end with "Error" if, and only if, they are derived from java.lang.Error.
Description
This audit rule finds types whose name ends with "Exception" but are not derived from java.lang.Exception, or classes that are derived from java.lang.Exception but whose name does not end in "Exception".
Example
The following class declaration would be flagged as a violation because the class name ends with "Exception" but it not derived from the class java.lang.Exception:
public class RequiredClassException { ... }
The following class declaration would be flagged as a violation because it is derived from the class java.lang.Exception but does not end with "Exception":
public class InvalidAuthorizationCode extends Exception { ... }
Severity: Medium
Summary
Constant names should conform to the defined standard.
Description
This audit rule checks the names of all static fields that are also final.
Example
If constant fields are specified as needing to consist only of uppercase letters and the underscore, the following declaration would be flagged as a violation:
public static final int DefaultCount = 0;
Severity: Medium
Summary
Constructors should only invoke final methods on the object being constructed.
Description
Subclasses can override non-final methods. Invoking them from a constructor can cause errors because the object is not in a a valid state.
Notes
Effective Java warns that "constructors must not invoke overridable methods, directly or indirectly." This rule catches the direct invocations.
Severity: Medium
Summary
Variables of certain types should be declared using an interface.
Description
This audit rule finds declarations of fields and variables whose type should have been declared to be an interface but was declared to be a class that implements the interface instead. The list of interfaces that are checked can be configured.
Example
If the type java.util.List is on the list of interfaces, the following would be flaged as a violation because the declared type of the field should have been "List":
private ArrayList myList;
Notes
This rule implements a portion of "design method signatures carefully" as described in Effective Java.
Severity: Medium
Summary
Native methods should be avoided because they are often platform dependent.
Description
Native methods should be avoided because they are often platform dependent.
Example
The following method declaraction would be flagged as a violation because it is implemented as a native method:
public int native getUID();
Notes
Java performance has gotten so good that it is rarely advisable to write native methods for performance reasons, according to Effective Java.
Severity: Medium
Summary
The sleep() method should not be used within a while loop.
Description
This audit rule looks for invocations of the sleep() method that occur inside of a while loop. Such occurances usually indicate that the code implements a busy-wait loop, which is inefficient. Instead, the code should use wait() and notify() to block the thread until it is possible for execution to proceed.
Example
The following invocation of the sleep() method would be flagged as a violation:
while (eventQueue.isEmpty()) { Thread.sleep(); }
Notes
A busy-wait loop relies on the thread scheduler, which is likely to exhibit non-portable performance characteristics. A better design is to suspend the thread by calling Object.wait(). Effective Java has an item devoted to this topic, "don't depend on the thread scheduler."
Severity: Medium
Summary
The class ThreadGroup should not be used.
Description
The class ThreadGroup should not be used in multi-threaded applications because its implementation is not thread safe.
Example
The following instance creation would be flagged as a violation because it is creating an instance of the class java.lang.ThreadGroup:
new ThreadGroup("Background Threads")
Notes
According to Effective Java "thread groups are largely obsolete."
Severity: Medium
Summary
Catch clauses should not be empty.
Description
This rule finds places where an exception is caught and nothing is done. It can be configured to allow the existence of a comment to substitute for actual Java code.
Example
try { ... } catch (Exception exception) { }
Notes
Effective Java makes this point: An empty catch block defeats the purpose of exceptions. At the very least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.
Severity: Medium
Summary
Flag classes that appear to follow the Singleton pattern but have a non-private constructor.
Description
Ensure that a class defined as a singleton follows specific rules that disallow multiple instances to be created. Singleton classes should have a single, private constructor and static access to the instance.
Notes
Using a private constructor ensures the class cannot be instantiated by another object. Effective Java describes two approaches to implementing singletons, both of which are supported by this rule. In addition, the singleton value may be computed by lazy initialization, which is also allowed by this rule.
Severity: Medium
Summary
Member classes should be defined as static classes when possible.
Description
This rule identifies member classes that are not defined as static classes but that could possibly be defined as such.
Notes
Static member classes do not require access to an enclosing instance. This makes them more flexible than non-static member classes, which can only be instantiatied in the context of an enclosing instance.
Severity: Medium
Summary
All fields should have a Javadoc comment associated with them.
Description
This audit rule checks for the existence of a Javadoc comment for each field. It can be configured to only flag fields with the specified visibilities.
Example
The following field declaration would be flagged as a violation because it does not have a Javadoc comment associated with it:
private String name;
Severity: Medium
Summary
Instance field names should conform to the defined standard.
Description
This audit rule checks the names of all instance fields.
Example
If the rule were configured to only allow instance fields to begin with a lower case letter, the following declaration would be flagged as a violation because it begins with an upper case letter:
private int MaxCount;
Severity: Medium
Summary
Interface names should conform to the defined standard.
Description
This audit rule checks the names of all interfaces.
Example
If the rule were configured to require that all interface names start with a capital "I" and another capital letter, the following declaration would be flagged as a violation because the name does not begin with a capital "I":
public interface EventListener { ... }
Severity: Medium
Summary
Label names should conform to the defined standard.
Description
This audit rule checks the names of all labels.
Example
If the rule were configured to require that labels begin with a lower case "l" and an upper case letter, the following label would be flagged as a violation because it does not begin with a lower case "l":
here: while (true) { ... }
Severity: Medium
Summary
Methods should not have too many parameters.
Description
This audit rule finds methods that have more than the specified number of parameters. Methods that exceed this number are likely to be too complex. Consider moving some of the values and behavior associated with them into a separate class.
Example
If the rule is configured to allow 4 parameters and a method with 12 parameters is found, that method will be flagged as a violation.
Notes
This rule implements a portion of "design method signatures carefully" as described in Effective Java.
Severity: Medium
Summary
Local variable names should conform to the defined standard.
Description
This audit rule checks the names of all local variables (parameters and temporary variables).
Example
If the rule were configured to only allow local variables to begin with a lower case letter, the following would be flagged as a violation because it starts with an underscore:
int _count;
Severity: Medium
Summary
All methods should have a Javadoc comment associated with them.
Description
This audit rule checks for the existence of a Javadoc comment for each method. In addition, it checks that each Javadoc comment includes a @param tag for each parameter (and none for non-parameters), a @return tag if the method has a return type other than void (and not if the return type is void, and a @throws tag for each explicitly declared exception (and none for exceptions that are not declared). It also checks for the use of the obsolete @exception tag.
Example
The Javadoc for the following method would be flagged three times as a violation, twice for missing @param tags and once for a missing @return tag:
/** * Return the sum. */ public int sum(int x, int y) { ... }
Severity: Medium
Summary
Method names should conform to the defined standard.
Description
This audit rule checks the names of all methods.
Example
If the rule were configured to only allow method names that begin with a lower case letter, the following method declaration would be flagged as a violation because the method name begins with an upper case letter:
public static Singleton GetInstance()
Notes
This rule implements a portion of "design method signatures carefully" as described in Effective Java.
Severity: Medium
Summary
Method parameter names should conform to the defined standard.
Description
This audit rule checks the names of all method parameters.
Example
If the rule were configured to only allow parameter names that begin with a lower case letter, the parameter in the following method declaration would be flagged as a violation because it begins with an underscore:
public void setCount(int _count)
Severity: Medium
Summary
Declare variables so that they have as small a scope as possible.
Description
This rule looks for variables whose scope is too broad. If a variable is declared without an initializer it is probably declared too early, and will be flagged. While-loops that could be converted to for-loops, reducing the scope of the iteration variable, are also detected.
Notes
Minimizing the scope of local variables helps reduce errors caused by mis-using variables, according to Effective Java. Variables should not be defined before they are needed, and they should be defined in the innermost block possible. Because of this the for-loop for iteration is preferred to the while-loop. for (Iterator iter = list.iterator(); iter.hasNext();) { Object element = iter.next(); ... }
Severity: Medium
Summary
Constructors in classes containing only static members should be private.
Description
This audit rule finds non-private constructors in classes containing only static members. There is no value in creating an instance of a type that contains only static members. To prevent such instantiation, ensure that type has a single, no-argument, private constructor and no other constructors.
Example
The following class declaration would be flagged as a violation:
public class Utilities { public static int getSize(List list) { ... } }
Notes
This rule implements the item that Effective Java calls "enforce noninstantiability with a private constructor".
Severity: Medium
Summary
Obey the general contract when overriding equals().
Description
The equals() method defined in Object is intended to be overridden by subclasses but each subclass must obey the general contract specified by the superclass. Classes should not use the name "equals" for methods that take any parameters other than a single Object. The body of the method should be coded defensively to accept any class of object as its argument.
Example
The style of equals() definition that this rule looks for is this:
public boolean equals(Object arg) { if (this == arg) return true; if (!(arg instanceof Foo)) return false; Foo fooArg = (Foo) arg; ... }
"Foo" is the name of a type, which is either the class that declares this equals() method or an interface that is implemented by that class.
Notes
This audit rules checks for compliance with the "recipe for a high-quality equals method" given in Effective Java. The steps in gives are: 1. Use == to determine if the argument is a reference to this object. 2. Use instanceof to check that the argument is of the proper type. The type can be the class that defines the equals() method, a subclass of it, or one of the interfaces it implements. 3. Cast the argument to the proper type. Once the argument has been cast to the proper type more specific attributes can be checked, as described in Effective Java. This rule only examines the more general steps outlined above. A sample method might look like this: public boolean equals(Object arg) { return this == arg || arg instanceof MyClass && ((MyClass)arg).isEqualTo(this); } In addition, this rule also flags methods that overload equals instead of overriding it.
Severity: Medium
Summary
Overloading method names can cause confusion and errors.
Description
This audit rule finds methods that are overloaded. Overloaded methods are methods that have the same name and the same number of parameters, but do not have the same types of parameters. Such methods can cause confusion and errors because it is not always obvious which method will be selected at run time.
Example
public void process(Person person) public void process(Employee employee)
Notes
Overloaded methods should be used with care. As Effective Java says "selection among overloaded methods is static, while selection among overriden methods is dynamic." In other words, selection of the method to invoke at runtime depends only on the class of the object, not on the classes of the arguments to the method.
Severity: Medium
Summary
Classes should override both equals() and hashCode() if they override either.
Description
This audit rule finds classes in which either the equals() or hashCode() method has been overridden, but not both.
Example
The following class declaration will be flagged as a violation because it overrides the method equals() but does not override the method hashCode():
public class Employee { private String name;
...
public boolean equals(Object object) { return object instanceof Employee && getName().equals(((Employee) object).getName()); } }
Notes
Equal objects must have equal hash codes. A common mistake is to omit a definition of hashCode() in a class that overrides equals(). It can lead to bugs that are VERY difficult to find. See Effective Java for an excellent description of how to create good hashCode methods.
Severity: Medium
Summary
Be careful when defining clone. It is complex and not fully specified.
Description
This audit rule helps to ensure that clone is used properly. It checks the following items: 1. Either the class is final or the clone method calls super.clone(). 2. Either the class is abstract or the clone method is declared public. 3. Either the class is final or the clone method declaration has the proper throws clause.
Notes
If you must use clone then you should use it responsibly, and this rule can help. The general contract of clone is not fully specified. Effective Java says clone methods function as another kind of constructor, however they do not work well with final fields.
Severity: Medium
Summary
Package names should conform to the defined standard.
Description
This audit rule checks the names of all packages as defined by the package declarations at the beginning of each compilation unit.
Example
If the rule has been configured to only allow package names consisting of lower case letters, the package name "utilitiyClasses" would be flagged as a violation because it contains an upper case letter.
Severity: Medium
Summary
Package names should begin with either a top-level domain name or a two-letter country code.
Description
This audit rule checks the names of all packages as defined by the package declarations at the beginning of each compilation unit to ensure that the first identifier is either a top-level domain name or a two-letter country code.
Example
For example, the following package declaration would be flagged as a violation because "freeware" is neither a top-level domain name nor a two-letter country code:
package freeware.model;
Severity: Low
Summary
It is better to define abstract types as interfaces than classes.
Description
This rule identifies types defined by abstract classes. It flags abstract classes that define public methods that are not defined in an interface implemented by the class.
Notes
When designing extensible types it is generally better to define the type as an interface and provide a skeletal implementation of the type in an abstract class. As Effective Java points out, interfaces allow the construction of nonhierarchical type frameworks.
Severity: Low
Summary
Consider using interfaces instead of reflection.
Description
This audit rule identifies uses of reflective capabilities and flags them for review. Much of what is accomplished via reflection can be done, faster and simpler, with judicious use of interfaces.
Notes
Use this rule as an aid to code review. It identifies reflective invocation of methods and constructors, and reflective field access. According to Effective Java these operations are usually more effective when done via an interface than reflection.
Severity: High
Summary
Questionable names may indicate sloppy code.
Description
This audit rule checks for questionable names of variables, fields, methods, and types. A questionable name may indicate sloppy code.
Three types of questionable names are flagged:
1. Names that occur in a user-configurable list.
2. Names that are shorter than a user-configurable size. Short names can be useful as for loop variables or in catch clauses so short names are not flagged if they occur in those two places.
3. Names that are longer than a user-configurable size.
Names that you always want to be accepted can be added to a list at the bottom of the preference pane. These names will be accepted whether or not they break any of the 3 rules given above.
Example
The variable "c" would be flagged as a violation in the following method because it is too short, but the variable "i" would not be because it is used as a loop variable:
public int getNonZeroElementCount() { int c;
c = 0; for (int i = 0; i < elements.size(); i++) { ... } return c; }
Severity: Medium
Summary
Return values should not be null.
Description
This audit rule finds places where null is returned rather than array types or simple types.
Example
The return statement in the following method would be flagged as a violation:
public int[] getRowSums() { if (table == null) { return null; } ... }
Notes
When the method definition implies the return value will be a collection of some sort it is best to return a zero-legth instance of the collection rather than null. Effective Java addresses array-typed methods, but the principle could also apply to collections.
Severity: Medium
Summary
Objects that cannot be modified at run-time should be created as static constants.
Description
This audit rule finds the creation of some kinds of immutable objects. An immutable object is an object whose state cannot be modified at run-time. Such objects should be created as constants (static final fields) so that in order to reduce the amount of garbage that must be collected.
Example
new Integer(5); new int[0];
Notes
This rule works with String Created from Literal and Temporary Object Creation to implement the item Effective Java calls "avoid creating duplicate objects".
Severity: Medium
Summary
Static fields should have names that conform to the defined standard.
Description
This audit rule checks the names of all static fields that are not also final.
Example
If the rule has been configured to allow only names that begin with an upper case letter, then the following declaration would be flagged as a violation:
public static int minutesPerHour = 60;
Severity: Medium
Summary
Strings should not be concatenated within a loop.
Description
The code to concatenate two strings is not very efficient because it creates a StringBuffer for each concatenation. When placed in a loop, this can result in the creation and collection of large numbers of temporary objects. You can create the StringBuffer before entering the loop, and append to it within the loop, thus reducing the overhead.
Example
String[] path; String result = ""; for (int i = 0; i < path.length; i++) { result = result + "." + path[i]; }
Notes
According to Effective Java "using the string concatenation operator repeatedly to concatenate N strings requires time quadratic in N." That's bad, especially in loops.
Severity: Medium
Summary
Strings should not be created from a String literal.
Description
This audit rule finds places in the code where a String literal is used to initialize a newly created String. Doing so is almost never necessary and usually only serves to waste both time and space.
Example
The following expression would be flagged as a violation:
new String("Pause");
Notes
This rule works with Reusable Immutables and Temporary Object Creation to implement the item Effective Java calls "avoid creating duplicate objects".
Severity: Low
Summary
Instances of numeric classes should not be created solely for the purpose of converting a numeric value to a string.
Description
This audit rule checks for the creation of numeric classes where the only purpose for the object is to invoke the toString() method on it. All of the numeric classes implement a static toString() method that can do the same thing, but without the cost of creating and collecting an extra object.
Example
The following expression would be flagged as a violation:
(new Integer(age)).toString()
Notes
This rule works with Reusable Immutables and String Created from Literal to implement the item Effective Java calls "avoid creating duplicate objects".
Severity: Medium
Summary
All types should have a Javadoc comment associated with them.
Description
This audit rule checks for the existence of a Javadoc comment for each type. It optionally checks for the existence of at least one @author tag and always ensures that every author tag has some text following it. It also optionally checks for the existence of at least one @version tag and always ensures that every version tag has some text following it.
Severity: Medium
Summary
Unnecessary exceptions should be removed.
Description
This audit rule checks for methods that declare an exception that cannot be thrown within the body of the method.
There are two options. The first controls whether unchecked exceptions will be allowed to be declared. This is sometimes desirable to allow the full range of exceptions to be fully documented.
The second option controls whether a class of exception can be declared when a subclass of the exception class is thrown, or whether only the classes of exceptions that are actually thrown can be declared.
Note: this rule does not examine the implementations of a method that occur in subclasses to see whether an exception is being declared in a superclass in order to allow it to be thrown by a method in a subclass.
Example
The following throws clause would be flagged as a violation because there is no way for the exception to be thrown:
public int getChildCount() throws RemoteException { return 0; }
Notes
See the item "avoid unnecessary use of checked exceptions" in Effective Java for a good discussion of the trade-offs in API design that revolve around checked exceptions.
Severity: Medium
Summary
Use interfaces to define types, not as places to store constants.
Description
This rule identifies interfaces that do not define any methods. Interfaces that do not define any fields are ignored.
Notes
While interfaces can be used as a convenient mechanism to give a class access to a group of constants, that practice is to be avoided. According to Effective Java: The constant interface pattern is a poor use of interfaces.
Severity: Medium
Summary
The wait() method should only be invoked within a while loop.
Description
This audit rule looks for invocations of the wait() method that occur outside of a while loop.
Example
The following invocation of the wait() method would be flagged as a violation:
public void waitForEvent() { synchronize (eventQueue) { eventQueue.wait(); ... } }
Notes
From Effective Java, this is the standard idiom for using the wait method:
synchronized (obj) {
while (