- ]]>
-
-
-
-
-
- Looks for use of iterators on synchronized collections built from the Collections class
-
As the collection in question was built thru Collections.synchronizedXXX, an assumption
- is made that this collection must be multithreaded safe. However, iterator access is used,
- which is explicitly unsafe. When iterators are to be used, synchronization should be done manually.
-
It is a slow detector
- ]]>
-
-
-
-
-
- Calculates the McCabe Cyclomatic Complexity measure and reports methods that have an
- excessive value. This report value can be set with system property 'fb-contrib.cc.limit'.
-
It is a slow detector
- ]]>
-
-
-
-
-
- Looks for parameters that are defined by classes, but only use methods defined by an
- implemented interface or super class. Relying on concrete classes in public signatures causes cohesion,
- and makes low impact changes more difficult.
-
It is a slow detector
- ]]>
-
-
-
-
-
- Looks for for loops that iterate over a java.util.List using an integer index, and get,
- rather than using an Iterator. An iterator may perform better depending List implementation,
- but more importantly will allow the code to be converted to other collections type.
-
It is a moderately fast detector
- ]]>
-
-
-
-
-
- Looks for collections or arrays that hold objects that are unrelated thru class or
- interface inheritance other than java.lang.Object. Doing so, makes for brittle code,
- relying either on positional correspondence for type, or a reliance on instanceof to
- determine type. A better design usually can be had by creating a seperate class,
- which defines the different types required, and add an instance of that class to the
- collection, or array.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that declare Runtime exceptions in their throws clause. While doing
- so is not illegal, it may represent a misunderstanding as to the exception in question.
- If a RuntimeException is declared, it implies that this exception type is expected to happen,
- which if true, should be handled in code, and not propogated.
-
It is a fast detector
- ]]>
-
-
-
-
-
- THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD
-
Looks for methods that use a high percentage of methods from another class over it's own
- methods. When this is the case, it is often better to implement this method in that other class,
- by refactoring the class to accept parameters it needs from the source class.
- The reporting percentage can be set with system property 'fb-contrib.ce.percent'.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that compare strings against literal strings, where the literal string
- is passed as the parameter. If the .equals or .compareTo is called on the literal itself, passing
- the variable as the parameter, you avoid the possibility of a NullPointerException.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for constructors of non final classes that make method calls to non final methods.
- As these methods could be overridden, the overridden method will be accessing an object that
- is only partially constructed, perhaps causing problems.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for constructors of non final classes that make method calls to non final methods.
- As these methods could be overridden, the overridden method will be accessing an object that
- is only partially constructed, perhaps causing problems.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for classes that maintain two or more lists or arrays associated one-for-one through the same index
- to hold two or more pieces of related information. It would be better to create a new class that holds
- all of these pieces of information, and place instances of this class in one list.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that correctly do not write to a parameter. To help document this, and to perhaps
- help the jvm optimize the invocation of this method, you should consider defining these parameters
- as final.
-
It is a slow detector
- ]]>
-
-
-
-
-
- Looks for abstract classes that define empty methods or methods that simply throw an
- exception. Since this is an abstract class, it may be cleaner to simple define this method
- as abstract, so that correct subclass behaviour is enforced.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that copy data from one array to another using a loop. It is
- better performing to use System.arraycopy to do such copying as this is a native method.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that use floating point indexes for loops. Since floating point
- math is inprecise, rounding errors will occur each time through the loop causing
- hard to find problems. It is usually better to use integer indexing, and calculating
- the correct floating point value from the index.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for method calls to collection classes where the method is not defined by the Collections
- interface, and an equivalent method exists in the interface. Examples include:
-
-
Old Method
New Method
-
Hashtable.contains
Map.containsValue
-
Hashtable.elements
Map.elements
-
Hashtable.keys
Map.keySet
-
Vector.addElement
List.add
-
Vector.elementAt
List.get
-
Vector.insertElementAt
List.add
-
Vector.removeAllElements
List.clear
-
Vector.removeElement
List.remove
-
Vector.removeElementAt
List.remove
-
Vector.setElementAt
List.set
-
-
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that have the same signature, except where one uses a
- Character parameter, and the other uses an int, long, float, double parameter.
- Since autoboxing is available in 1.5 one might assume that
-
- test('a')
-
- would map to
-
- public void test(Character c)
-
- but instead maps to one that takes an int long, float or double.
-
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that have finally blocks that return values
- or throw exceptions. This code will swallow normal program flow and
- hide real program logic.
-
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that make static method calls using an instance reference.
- For documentation purposes, it is better to call the method using the class name.
- This may represent a change in definition that should be noticed.
-
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that call wait, notify or notifyAll on an instance of a
- java.lang.Thread. Since the internal workings of the threads is to synchronize on the
- thread itself, introducing client calls will confuse the thread state of the object
- in question, and will cause spurious thread state changes, either waking threads up
- when not intended, or removing the thread from the runnable state.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that pass a primitive wrapper class object, to the
- same classes Constructor. Patterns found are:
-
-
new Boolean(Boolean)
-
new Byte(Byte)
-
new Character(Character)
-
new Short(Short)
-
new Integer(Integer)
-
new Long(Long)
-
new Float(Float)
-
new Double(Double)
-
-
-
It also looks for calls to BoxedClass.valueOf(x) where X is already a Boxed class
-
It also looks for calls to BoxedClass.valueOf(myString).boxedValue(), When instead it is
- simpler to use BoxedClass.parseBoxed(myString)
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that store the return result in a local variable, and
- then immediately returns that local variable.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that are direct copies of the implementation in the super class
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that use arrays for items in the keyset of a map, or as
- an element of a set, or in a list when using the contains method. Since arrays
- do not, and cannot define an equals method, reference equality is used for these
- collections, which is probably not desired. If it is, consider using the IdentityHashMap
- class when using Maps in this case, to better document your intentions.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that create DOM Nodes but do not add them to any DOM Document.
-
It is a fast Detector
- ]]>
-
-
-
-
-
- Looks for methods that are declared as abstract that override concrete methods in a
- super class. Doing this casts away the implementation of the super class, and breaks
- the contract as set forth by the parent class.
-
It is a fast Detector
- ]]>
-
-
-
-
-
- Looks for methods that build xml based strings by concatenation strings
- and custom values together. Doing so makes brittle code, that is difficult to
- modify, validate and understand. It is cleaner to create external xml files that are
- transformed at runtime, using parameters set through Transformer.setParameter.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that are implemented using synchronized blocks, but are overly
- synchronized because the beginning of the block only accesses local variables,
- and not member variables, or this.
-
It is a slow detector
- ]]>
-
-
-
-
-
- Looks for methods that access arrays or classes that implement java.util.List
- using a constant integer for the index. This is often a typo intented to be a loop
- variable, but if specific indices mean certain things, perhaps a first class object
- would be a better choice for a container.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that use Class.forName("XXX") to load a class object
- for a class that is already referenced by this class. It is simpler to just use
- XXX.class, and doing so protects the integrity of this code from such transformations
- as obfuscation. Use of Class.forName should only be used when the class in question
- isn't already statically bound to this context.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that use an array of length one to pass a variable to achieve call
- by pointer ala C++. It is better to define a proper return class type that holds all
- the relevant information retrieved from the called method.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that implement awt or swing listeners and perform time
- consuming operations. Doing these operations in the gui thread will cause the
- interface to appear sluggish and non-responsive to the user. It is better to
- use a separate thread to do the time consuming work so that the user
- has a better experience.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for methods that call a method to retrieve a reference to an object,
- to use to load a constant. It is simpler and more performant to access the
- static variable directly from the class itself.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for inefficient comparison of Date objects using two comparisons when one would do.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for calls to the wait method on mutexes defined in the java.util.concurrent
- package where it is likely that await was intended.
-
It is a fast detector
- ]]>
-
-
-
-
-
- Looks for uses of jdbc vendor specific classes and methods making the database
- access code non portable.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for classes that maintain collections or StringBuffer/StringBuilders in
- static member variables, and that do not appear to provide a way to clear or remove
- items from these members. Such class fields are likely causes of memory bloat.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for allocations of synchronized collections that are stored in local
- variables, and never stored in fields or returned from methods. As local variables
- are by definition thread safe, using synchronized collections in this context
- makes no sense.
-
It is a moderately fast detector
- ]]>
-
-
-
-
-
- looks for classes that define fields that are used in a locals only fashion,
- specifically private fields that are accessed first in each method with a
- store vs. a load.
-
It is a slow detector
- ]]>
-
-
-
-
-
- looks for methods that synchronize on variables that are not owned by the
- current class. Doing this causes confusion when two classes use the same variable
- for their own synchronization purposes. For cleanest separation of interests, only
- synchronize on private fields of the class. Note that 'this' is not owned by
- the current class and synchronization on 'this' should be avoided as well.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for tag libraries that are not recycleable because backing members
- of taglib attributes are set in areas besides the setter method for the attribute.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for violation of Section 508, Accessibility for People with disabilities Act.
-
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for use of sets and maps using enums. It is more efficient to use EnumSet or EnumMap
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for the execution of sql queries inside a loop. This pattern tends to be inefficient,
- and often can be improved upon, by collecting all the keys needed for the query and issuing just
- one query using an in clause with all the keys for all the queries previously needed in the loop.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for classes that define private synchronized collections as static or instance
- members, that are only altered in a static initializer or constructor. Since the multithreaded
- use of this collection is read-only, the use of synchronization is unnecessary.
-
It is a moderately fast detector
- ]]>
-
-
-
-
-
- looks for if/else blocks where a series of them use instanceof on the same
- variable to determine what to do. If these classes are related by inheritance,
- this often is better handled through calling a single overridden method.
-
It is a moderately fast detector
- ]]>
-
-
-
-
-
- looks for creation of arrays in methods using constant values. These arrays
- will need to be recreated each time the method is called. These arrays should probably
- be defined as static fields, instead
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for calls of the same method on the same object when that object hasn't changed.
- This often is redundant, and the second call can be removed, or combined.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for code that builds an array of values from a collection, by manually looping
- over the elements of the collection, and adding them to the array. It is simpler and
- cleaner to use mycollection.toArray(new type[mycollection.size()].
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for methods that catch exceptions, and then throw a different exception,
- without embedding the original exception in the thrown one. Doing so, hides the real
- source of the exception, making debugging and fixing these problems difficult.
-
It is a moderately fast detector
- ]]>
-
-
-
-
-
- looks for methods that pass single character string constants as parameters to
- methods that alternatively have an overridden method that accepts a character instead.
- It is easier for the method to handle a single character than a String.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for methods that make a recursive call to itself as the last statement in the
- method. This tail recursion could be converted into a simple loop which would improve
- the performance and stack requirements.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for methods that are defined to return Object, and return different types of
- objects based on different code paths. If this method is not based on a interface or
- superclass, it is suggested to change the return type to a type that would accomodate
- all kinds of return types.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for classes that don't handle serialization of parent class member fields
- when the class in question is serializable but is derived from a non serializable
- classes.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for class that implement Comparator or Comparable, and whose compare or compareTo
- methods return constant values only, but that don't represent the three possible choice
- (a negative number, 0, and a positive number).
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for a potpourri of small problems that do not fit into a common pattern.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD
- Looks for assignments to variables in a scope larger than it's use. As long as the evaluation of the assignment
- does not have side effects, the assignment can be moved into the inner scope where it is used.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for classes that implement interfaces by relying on methods being
- implemented in superclasses, even tho the superclass knows nothing about
- the interface being implemented by the child.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for deletion of items from a collection using the remove method
- of the collection at the same time that the collection is being iterated on. If
- this occurs the iterator will become invalid and throw a ConcurrentModificationException.
- Instead, the remove should be called on the iterator itself.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for code that builds an array by using a StringTokenizer to break up
- a string and place individual elements into an array. It is simpler to use
- String.split instead.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for calls to classes and methods that do not exist in the JDK for which this class is
- compiled. This can happen if you specify the -source and -target options of the javac compiler, and
- specify a target that is less than the jdk version of the javac compiler.
-
It is a slow detector.
- ]]>
-
-
-
-
-
- looks for loops that transfers the contents of one collection to another. These collection sources might
- be local variables or member fields, including sets, maps key/values, lists, or arrays. It is simpler to
- just use the addAll method of the collection class. In the case where the source is an array, you can use
- Arrays.asList(array), and use that as the source to addAll.
-
It is a fast detector.
- ]]>
-
-
-
-
-
- looks for private methods that only return one constant value. Since there is no
- chance for derived classes overriding this behavior, the return of a constant value
- seems dubious.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for classes that implement the Serializable interface and implement the
- standard readObject and writeObject methods by simply deferring to the Stream
- parameter's defaultReadObject or defaultWriteObject and nothing else. As this is the
- built in behavior, these methods are not needed.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for classes that define both static and instance methods with the same name.
- As each type represents a different use model, it doesn't make sense that this name
- would be overloaded, and will confuse users of the class.
-
It is a fast detector
- ]]>
-
-
-
-
-
- looks for methods that catch checked exceptions, and throw unchecked
- exceptions in their place. There are several levels of concern. Least
- concerning are methods constrained by interface or super class contracts
- not to throw checked exceptions but appear owned by the same author. Next
- are methods constrained by interface or super class contracts and throw other
- types of checked exceptions. Most egregious are method not constrained by any interface
- or superclass contract.
-
It is a moderately fast detector
- ]]>
-
-
-
-
-
- looks for methods that return a parameter after modifying that parameter.
- Doing this will confuse the user of this method, as it will be assumed that the
- passed in argument is different than the output, or at least won't be changed.
- If the purpose of this method is just to modify the parameter, this method should
- probably be changed to have a void return type. If you must return a variable, perhaps
- a clone of the parameter should be returned.
-
-
It is a fast detector
- ]]>
-
-
-
-
-
-
- method passes simple concatenating string in StringBuffer or StringBuilder append
- method {1} passes simple concatenating string in StringBuffer or StringBuilder append
-
- This method uses StringBuffer or StringBuilder append to concatenate strings. However, it passes the result
- of doing a simple String concatenation to one of these append calls, thus removing any performance gains
- of using the StringBuffer or StringBuilder class.
- ]]>
-
-
-
-
- method concatenates an empty string to effect type conversion
- method {1} concatenates an empty string to effect type conversion
-
- This method concatenates an empty string with a literal value, in order to convert
- the literal value into a string. It is more efficient to use String.valueOf() to do the same
- thing as you do not incur the cost of creating a StringBuffer/Builder and calling methods on it
- to accomplish this.
- ]]>
-
-
-
-
- method creates iterators on synchronized collections
- method {1} creates iterators on synchronized collections
-
- This method uses a synchronized collection, built from Collections.synchronizedXXXX, but accesses it
- through an iterator. Since an iterator is by definition, multithreaded unsafe, this is a conflict in
- concept. When using iterators, you should do the synchronization manually.
- ]]>
-
-
-
-
- method is excessively complex
- method {1} is excessively complex
-
- This method has a high cyclomatic complexity figure, which calculates the number of branch
- points. It is likely difficult to test, and is brittle to change. Consider refactoring this
- method into several to reduce the risk.
- ]]>
-
-
-
-
- method needlessly defines parameter with concrete classes
- method {1} needlessly defines parameter with concrete classes
-
- This method uses concrete classes for parameters when only methods defined in an implemented
- interface or super class are used. Consider increasing the abstraction of the interface to
- make low impact changes easier to accomplish in the future.
- ]]>
-
-
-
-
- method uses integer based for loops to iterate over a List
- method {1} uses integer based for loops to iterate over a List
-
- This method uses an integer based for loop to iterator over a java.util.List, by calling
- List.get(i) each time thru the loop. The integer is not used for other reasons. It is better
- to use an Iterator instead, as depending on List implementation, iterators can perform better,
- and they also allow for exchanging of other collection types without issue.
- ]]>
-
-
-
-
- method adds unrelated types to collection or array
- method {1} adds unrelated types to collection or array
-
- This method adds unrelated objects to a collection or array, requiring careful and brittle
- data access to that collection. Create a separate class with properties needed, and add
- an instance of this class to the collection or array, if possible.
- ]]>
-
-
-
-
- method declares RuntimeException in throws clause
- method {1} declares RuntimeException in throws clause
-
- This method declares a RuntimeException derived class in it's throws clause.
- This may indicate a misunderstanding as to how unchecked exceptions are handled.
- If is felt that a RuntimeException is so prevalent that it should be declared, it
- is probably a better idea to prevent the occurance in code.
- ]]>
-
-
-
-
- method excessively uses methods of another class
- method {1} excessively uses methods of another class
-
- THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD
-
This method makes extensive use of methods from another class over methods of it's own
- class. Typically this means that the functionality that is accomplished by this method
- most likely belongs with the class that is being used so liberally. Consider refactoring this
- method to be contained in that class, and to accept all the parameters needed in the method signature.
- ]]>
-
-
-
-
- method makes literal string comparisons passing the literal as an argument
- method {1} makes literal string comparisons passing the literal as an argument
-
- This method calls the equals or compareTo methods on a String variable passing in a String literal.
- A NullPointerException may occur if the string variable is null. If instead the method was called on
- the string literal, and the variable was passed as an argument, this exception could never happen.
- ]]>
-
-
-
-
- constructor makes call to non-final method
- constructor {1} makes call to non-final method
-
- This constructor makes a call to a non-final method. Since this method can be overriden, a subclasses
- implementation will be executing against an object that has not been initialized at the subclass level.
- You should mark all methods called from the constructor as final to avoid this problem.
- ]]>
-
-
-
-
- class defines List based fields but uses them like Sets
- class {0} defines List based fields but uses them like Sets
-
- This class defines a field based on java.util.List, but uses it to some extent like a Set. Since
- lookup type operations are performed using a linear search for Lists, the performance for large
- Lists will be poor. Consider changing this fields implementation to a set based one. If order of
- iteration is important to maintain insert order, perhaps consider a LinkedHashSet.
- ]]>
-
-
-
-
- class defines two or more one for one associated lists or arrays
- class {0} defines two or more one for one associated lists or arrays
-
- This class appears to maintain two or more lists or arrays who's contains is related one-for-one
- through the index of the list or array. Consider creating a separate class to hold all the related
- pieces of information, and adding instances of this class to just one list or array.
- ]]>
-
-
-
-
- method does not define a parameter as final, but could
- method {1} does not define a parameter as final, but could
-
- This method correctly does not write to a parameter. To help document this, and to perhaps
- help the jvm optimize the invocation of this method, you should consider defining these parameters
- as final.
- ]]>
-
-
-
-
- empty method could be declared abstract
- empty method {1} could be declared abstract
-
- This method is empty or merely throws an exception. Since the class it is defined in is
- abstract, it may be more correct to define this method as abstract instead, so that proper
- subclass behavior is enforced.
- ]]>
-
-
-
-
- method copies arrays manually
- method {1} copies arrays manually
-
- This method copies data from one array to another manually using a loop.
- It is much better performing to use System.arraycopy as this method is native.
- ]]>
-
-
-
-
- method uses floating point indexed loops
- method {1} uses floating point indexed loops
-
- This method uses floating point variables to index a loop. Since floating point
- math is inprecise, rounding errors will accumulate over time each time the loop is
- executed. It is usually better to use integer indexing, and calculate the new value
- of the floating point number at the top of the loop body.
- ]]>
-
-
-
-
- method uses old non collections interface methods
- method {1} uses old non collections interface methods
-
- This method makes calls to collection classes where the method is not defined by the Collections
- interface, and an equivalent method exists in the interface. By using the new methods,
- you can define this object by the Collections interface and allow better decoupling.
- ]]>
-
-
-
-
- class defines methods which confuse Character with int parameters
- class {0} defines methods which confuse Character with int parameters
-
- This class defines two methods that differ only by a parameter being defined
- as Character vs. int, long, float or double. As autoboxing is present, it may be
- assumed that a parameter of 'a' would map to the Character version, but does not.
- ]]>
-
-
-
-
- class has abnormal exit from finally block
- class {0} has abnormal exit from finally block
-
- This class returns or throws exceptions from a finally block. This will
- mask real program logic in the try block, and short-circuit normal method termination.
-
- ]]>
-
-
-
-
- method calls static method on instance reference
- method {1} calls static method on instance reference
-
- This method makes a static method call on an instance reference. For
- reading comprehension of the code is better to call the method on the class,
- rather than an instance. Perhaps this method's static nature has changed since
- this code was written, and should be revisited.
-
- ]]>
-
-
-
-
- method calls wait, notify or notifyAll on a Thread instance
- method {1} calls wait, notify or notifyAll on a Thread instance
-
- This method invokes the methods wait, notify or notifyAll on a Thread instance.
- Doing so will confuse the internal thread state behaviour causing spurious thread
- wakeups/sleeps because the internal mechanism also uses the thread instance for it's
- notifications.
-
- ]]>
-
-
-
-
- method passes primitive wrapper to same primitive wrapper constructor
- method {1} passes primitive wrapper to same primitive wrapper constructor
-
- This method passes a wrapped primitive object to the same class's constructor.
- Since wrapper classes are immutable, you can just use the original object, rather
- than constructing a new one. This code works because of an abuse of autoboxing.
-
- ]]>
-
-
-
-
- method passes parsed string to primitive wrapper constructor
- method {1} passes parsed string to primitive wrapper constructor
-
- This method passes a primitive value retrieved from a BoxedPrimitive.parseBoxedPrimitive("1") call to
- the same class's constructor. It is simpler to just pass the string to the BoxedPrimitives constructor.
-
- ]]>
-
-
-
-
- method passes primitive wrapper to Wrapper class valueOf method
- method {1} passes primitive wrapper to Wrapper class valueOf method
-
- This method passes a wrapped primitive object to the same class's .valueOf method.
- Since wrapper classes are immutable, you can just use the original object, rather
- than calling valueOf to create a new one. This code works because of an abuse of autoboxing.
-
- ]]>
-
-
-
-
- method converts String to primitive using excessive boxing
- method {1} converts String to primitive using excessive boxing
-
- This method passes a String to a wrapped primitive object's valueOf method, which in turn calls
- the boxedValue() method to convert to a primitive. When it is desired to convert from a String
- to a primitive value, it is simpler to use the BoxedPrimitive.parseBoxedPrimitive(myString)
- method.
- ]]>
-
-
-
-
- method converts String to boxed primitive using excessive boxing
- method {1} converts String to boxed primitive using excessive boxing
-
- This method passes a String to a wrapped primitive object's parse method, which in turn calls
- the valueOf() method to convert to a boxed primitive. When it is desired to convert from a String
- to a boxed primitive object, it is simpler to use the BoxedPrimitive.valueOf(myString)
- method.
- ]]>
-
-
-
-
- method creates Boxed primitive from primitive only to get primitive value
- method {1} creates Boxed primitive from primitive only to get primitive value
-
- This method constructs a Boxed Primitive from a primitive only to call the primitiveValue() method to
- convert it back to a primitive. Just use the primitive value instead.
-
- primitive i = new BoxedPrimitive(1).primitiveValue();
- or
- primitive i = BoxedPrimitive.valueOf(1).primitiveValue();
-
- should just use
- primitive i = 1;
-
- ]]>
-
-
-
-
- method creates Boxed primitive from primitive only to cast to another primitive type
- method {1} creates Boxed primitive from primitive only to cast to another primitive type
-
- This method constructs a Boxed Primitive from a primitive only to call the primitiveValue() method to
- cast the value to another primitive typee. It is simpler to just use casting
-
- primitive i = new BoxedPrimitive(1.0).primitiveValue();
- or
- primitive i = BoxedPrimitive.valueOf(1.0).primitiveValue();
-
- should just use
- primitive i = (primitive)1.0;
-
- ]]>
-
-
-
-
- method stores return result in local before immediately returning it
- method {1} stores return result in local before immediately returning it
-
- This method stores the return result in a local variable, and then immediately
- returns the local variable. It would be simpler just to return the value that is
- assigned to the local variable, directly.
-
- ]]>
-
-
-
-
- method is implemented with an exact copy of it's superclass's method
- method {1} is implemented with an exact copy of it's superclass's method
-
- This method is implemented using an exact copy of it's super class method's
- implementation, which usually means that this method can just be removed.
-
- ]]>
-
-
-
-
- method uses array as basis of collection
- method {1} uses array as basis of collection
-
- This method passes an array as the key to a Map, element in a Set, or item in a List when
- the contains method is used on the List. Since arrays do not, and cannot override the equals
- method, collection inclusion is based on the reference's address, which is probably not desired.
- In the case that this is a TreeMap or TreeSet, consider passing a Comparator to the map's
- constructor.
-
- ]]>
-
-
-
-
- method creates DOM node but doesn't attach it to a document
- method {1} creates DOM node but doesn't attach it to a document
-
- This method creates a DOM node but does not attach it to a DOM document.
-
- ]]>
-
-
-
-
- abstract method overrides a concrete implementation
- abstract method {1} overrides a concrete implementation
-
- This abstract method is derived from a concrete method implementation. It is highly
- suspect that the super class method's implementation would be cast away.
-
- ]]>
-
-
-
-
- method builds xml strings through adhoc concatenation
- method {1} builds xml strings through adhoc concatenation
-
- This method generates an xml based string by concatenating together various
- xml fragments, and variable values. Doing so makes the code difficult to read, modify
- and validate. It is much more clean to built xml structures in external files that are
- read in and transformed into the final product, thru modification by Transformer.setParameter.
-
- ]]>
-
-
-
-
- method overly synchronizes a block of code
- method {1} overly synchronizes a block of code
-
- This methods implements a synchronized block, but the code found at the beginning
- of this block only accesses local variables, and not member variables, or this.
- To be better performance move the code that access local variables only, above the
- synchronized block, and leave the synchronized block only for field accesses, or access
- to this object.
- ]]>
-
-
-
-
- method accesses list or array with constant index
- method {1} accesses list or array with constant index
-
- This method accesses an array or list using a constant integer index. Often,
- this is a typo where a loop variable is intended to be used. If however, specific
- list indices mean different specific things, then perhaps replacing the list with
- a first-class object with meaningful accessors would make the code less brittle.
- ]]>
-
-
-
-
- method accesses statically bound class with Class.forName
- method {1} accesses statically bound class with Class.forName
-
- This method accesses the class object of a class that is already statically bound
- in this context, with Class.forName. Using Class.forName makes reflection more fragile
- in regards to code transformations such as obfuscation, and is unneeded here, since
- the class in question is already 'linked' to this class.
- ]]>
-
-
-
-
- method uses 1 element array to simulate call by reference
- method {1} uses 1 element array to simulate call by reference
-
- This method uses a one element array to wrap an object that is to be past to a method as an argument
- to simulate call by pointer ala C++. It is better to define a proper return class type that holds all
- the relevant information retrieved from the called method.
- ]]>
-
-
-
-
- method performs time consuming operation in gui thread
- method {1} performs time consuming operation in gui thread
-
- This method implements an awt or swing listener and performs time
- consuming operations. Doing these operations in the gui thread will cause the
- interface to appear sluggish and non-responsive to the user. Consider
- using a separate thread to do the time consuming work so that the user
- has a better experience.
- ]]>
-
-
-
-
- method retrieves instance to load static member
- method {1} retrieves instance to load static member
-
- This method calls a method to load a reference to an object, and then only
- uses it to load a static member of that instance's class. It is simpler and
- better performant to just load the static field from the class itself.
- ]]>
-
-
-
-
- Method uses two date comparisons when one would do
- Method {1} uses two date comparisons when one would do
-
- This method compares dates with two comparisons, rather than using the reverse comparison.
- So This pattern
-
- if ((date1.equals( date2 )) || (date1.after( date2 )))
-
- could become
-
- if (!date2.before( date1 ))
-
- and
-
- if ((date1.equals( date2 )) || (date1.before( date2 )))
-
- could become
-
- if (!date2.after( date1 ))
-
- and
-
- if ((date1.before( date2 )) || (date1.after( date2 )))
-
- could become
-
- if (!date1.equals( date2 ))
-
- ]]>
-
-
-
-
- method calls wait when await was probably intended
- method {1} calls wait when await was probably intended
-
- This method calls wait() on a on mutex defined in the java.util.concurrent package.
- These classes, define await, instead of wait, and it is most likely that await
- was intended.
- ]]>
-
-
-
-
- method uses jdbc vendor specific classes and methods
- method {1} uses jdbc vendor specific classes and methods
-
- This method uses jdbc vendor specific classes and method to perform database work.
- This makes the code specific to this vendor, and unable to run on other databases.
- ]]>
-
-
-
-
- class defines static field that appears to allow memory bloat
- class {0} defines static field that appears to allow memory bloat
-
- This class defines static fields that are collections or StringBuffers that do not
- appear to have any way to clear or reduce their size. This is a potential cause of
- memory bloat.
- ]]>
-
-
-
-
- method creates local variable-based synchronized collection
- method {1} creates local variable-based synchronized collection
-
- This method creates a synchronized collection and store the reference to it
- in a local variable. As local variables are by definition threadsafe, it seems
- questionable that this collection needs to be synchronized.
-
-
-
If you are using
consider using
-
java.util.Vector
java.util.ArrayList
-
java.util.Hashtable
java.util.HashMap
-
java.lang.StringBuffer
java.lang.StringBuilder
-
-
- ]]>
-
-
-
-
- class defines fields that are used only as locals
- class {0} defines fields that are used only as locals
-
- This class defines fields that are used in a locals only fashion,
- specifically private fields or protected fields in final classes that are accessed
- first in each method with a store vs. a load. This field could be replaced by one
- or more local variables.
- ]]>
-
-
-
-
- class uses non owned variables to synchronize on
- class {0} uses non owned variables to synchronize on
-
- This method uses a synchronize block where the object that is being synchronized on,
- is not owned by this current instance. This means that other instances may use this same
- object for synchronization for its own purposes causing synchronization confusion. It is
- always cleaner and safer to only synchronize on private fields of this class. Note that 'this'
- is not owned by the current instance, but is owned by whomever assigns it to a field of its
- class. Synchronizing on 'this' is also not a good idea.
- ]]>
-
-
-
-
- Tag library is not recycleable
- Tag library {0} is not recycleable
-
- This Tag library class implements an attribute who's associated backing store field
- is modified at another point in the tag library. In order for a taglibrary to be
- recycleable, only the container is allowed to change this attribute, through the use
- of the setXXX method of the taglib. By modifying the value programmatically, the
- container will not initialize the attribute correctly on reuse.
- ]]>
-
-
-
-
- Gui uses absolute layout
- Gui {0} uses absolute layout
-
- This class passes null to setLayout, which specifies that components are
- to be laid out using absolute coordinates. This makes making changes for
- font sizes, etc, difficult as items will not reposition
-
- ]]>
-
-
-
-
- JLabel doesn't specify what it's labeling
- JLabel in method {1} doesn't specify what it's labeling
-
- This class uses JLabels that do not specify what fields are being labeled.
- This hampers screen readers from given appropriate feed back to users. Use
- the JLabel.setLabelFor method to accomplish this.
-
- ]]>
-
-
-
-
- Window sets size manually, and doesn't use pack
- Window {0} sets size manually, and doesn't use pack
-
- This class creates a window, and sizes the window using setSize. It is better
- to handle font size changes to use the pack method.
-
- ]]>
-
-
-
-
- Class extends JComponent but does not implement Accessible interface
- Class {0} extends JComponent but does not implement Accessible interface
-
- This class extends the JComponent gui control but does not implement the Accessibility interface.
- This makes this control unable to be processed by screen readers, etc, for people with reading/vision
- difficulties
- ]]>
-
-
-
-
- Method explicitly sets the color of a Component
- Method {1} Method explicitly sets the color of a Component
-
- This method sets a Components explicitly foreground or background color which may
- cause difficulty with people with vision problems from using this application.
- Colors should be allowed to be set from the operating system.
- ]]>
-
-
-
-
- Class uses an ordinary set or map with an enum class as the key
- Class {0} uses an ordinary set or map with an enum class as the key
-
- This class uses an ordinary set or map collection and uses an enum class as the key type.
- It is better performant to use the jdk 1.5 EnumSet or EnumMap classes.
- ]]>
-
-
-
-
- Method executes sql queries inside of loops
- Method {1} executes sql queries inside of loops
-
- This method executes sql queries inside of a loop. This pattern is often inefficient
- as the number of queries may mushroom in fencepost cases. It is probably more performant
- to loop over the input and collect the key data needed for the query for all items, and
- issue one query using an in clause, or similar construct, and then loop over this result
- set, and fetch all the data at once.
- ]]>
-
-
-
-
- Class defines unneeded synchronization on member collection
- Class {0} defines unneeded synchronization on member collection
-
- This class defines a private collection member as synchronized. It appears however
- that this collection isn't only modified in a static initializer, or constructor. As these
- two areas are guaranteed to be thread safe, defining this collection as synchronized is
- unnecessary and a potential performance bottleneck.
- ]]>
-
-
-
-
- Method uses instanceof on multiple types to arbitrate logic
- Method {1} uses instanceof on multiple types to arbitrate logic
-
- This method uses the instanceof operator in a series of if/else statements to
- differentiate blocks of code based on type. If these types are related by inheritance,
- it is cleaner to just define a method in the base class, and use overridden methods
- in these classes.
- ]]>
-
-
-
-
- Method creates array using constants
- Method {1} creates array using constants
-
- This method creates an array initialized by constants. Each time this method is called
- this array will be recreated. It would be more performant to define the array as a
- static field of the class instead.
- ]]>
-
-
-
-
- Method appears to call the same method on the same object redundantly
- Method {1} appears to call the same method on the same object redundantly
-
- This method makes two consecutive calls to the same method using the same constant
- parameters, on the same instance without any intervening changes to the objects. If this
- method does not make changes to the object, which it appears it doesn't, then making
- two calls is just a waste. These method calls could be combined by assigning the
- result into a temporary, and using the temporary the second time.
- ]]>
-
-
-
-
- Method manually creates array from collection
- Method {1} manually creates array from collection
-
- This method manually loops over a collection, pulling each element out and storing
- it in an array to build an array from the collection. It is easier, and clearer to use
- the built in collections method toArray. Given a collection 'mycollection' of type T, use
- mycollection.toArray(new T[mycollection.size()]);
- ]]>
-
-
-
-
- Method throws alternative exception from catch block without history
- Method {1} throws alternative exception from catch block without history
-
- This method catches an exception, and throws a different exception, without incorporating the
- original exception. Doing so hides the original source of the exception making debugging and fixing
- these problems difficult. It is better to use the constructor of this new exception that takes an
- original exception so that this detail can be passed along to the user.
- ]]>
-
-
-
-
- Method passes constant String of length 1 to character overridden method
- Method {1} passes constant String of length 1 to character overridden method
-
- This method passes a constant literal String of length 1 as a parameter to a method, that
- exposes a similar method that takes a character. It is simpler and more expedient to handle one
- character, rather than pass a string.
- ]]>
-
-
-
-
- Method employs tail recursion
- Method {1} employs tail recursion
-
- This method recursively calls itself as the last statement of the method
- (Tail Recursion). This method can be easily refactored into a simple loop, which
- will make it more performant, and reduce the stack size requirements.
- ]]>
-
-
-
-
- Method returns different types of unrelated Objects
- Method {1} returns different types of unrelated Objects
-
- This method returns two or more unrelated types of objects (Related only through java.lang.Object).
- This will be very confusing to the code that must call it.
- ]]>
-
-
-
-
- Method returns more specific type of object than declared
- Method {1} returns more specific type of object than declared
-
- This method is defined to return a java.lang.Object. However, the return types
- returned from this method can be defined by a more specific class or interface. Since this
- method is not derived from a superclass or interface, it would be more clear to
- change the return type of this method.
- ]]>
-
-
-
-
- Inherited method returns more specific type of object than declared
- Inherited method {1} returns more specific type of object than declared
-
- This inherited method is defined to return a java.lang.Object. However, the return types returned
- from this method can be defined by a more specific class or interface. If possible consider changing the
- return type in the inheritance hierarchy of this method, otherwise the caller of this method will be brittle
- in handling of the return type.
- ]]>
-
-
-
-
- Class doesn't serialize superclass fields
- Class {0} doesn't serialize superclass fields
-
- This method implements Serializable but is derived from a
- class that does not. The super class has fields that are not serialized
- because this class does not take the responsibility of writing these fields out
- either using Serializable's writeObject method, or Externalizable's writeExternal
- method. Therefore when this class is read from a stream, the superclass fields
- will only be initialized to the values specified in it's default constructor.
- If possible, change the superclass to implement Serializable, or implement
- Serializable or Externalizable methods in the child class.
- ]]>
-
-
-
-
- Comparator method doesn't seem to return all ordering values
- Comparator method {1} doesn't seem to return all ordering values
-
- This compareTo or compare method returns constant values for to represent less than,
- equals and greater than. However it does not return each type. Given that comparators
- are transitive, this seems incorrect.
- ]]>
-
-
-
-
- Method passes a negative number as a bit to a BitSet which isn't supported
- Method {1} passes a negative number as a bit to a BitSet which isn't supported
-
- This method passes a constant negative value as a bit position to a java.util.BitSet. The BitSet class
- doesn't support negative values, and thus this method call will not work as expected.
- ]]>
-
-
-
-
- Method calls intern on a string constant
- Method {1} calls intern on a string constant
-
- This method calls intern on a constant string. As constant strings are already interned, this call
- is superfluous
- ]]>
-
-
-
-
- Method appears to pass character to StringBuffer or StringBuilder integer constructor
- Method {1} appears to pass character to StringBuffer or StringBuilder integer constructor
-
- This method constructs a StringBuffer or a StringBuilder using the constructor that takes an integer, but
- appears to pass a character instead. It is probable that the author assumed that character would be appended to the
- StringBuffer/Builder, but instead the integer value of the character is used as an initial size for the buffer.
-
- ]]>
-
-
-
-
- Method uses non standard math constant
- Method {1} uses non standard math constant
-
- This method defines its own version of PI or e and the value is not as precise as the
- one defined in the constants Math.PI or Math.E. Use these constants instead.
- ]]>
-
-
-
-
- Method assigns a value to a local twice in a row
- Method {1} assigns a value to a local twice in a row
-
- This method assigns a value twice in a row in a stuttered way such as
- a = a = 5; This is most probably a cut and paste error where the duplicate
- assignment can be removed.
- ]]>
-
-
-
-
- Method compares a double to Double.NAN
- Method {1} compares a double to Double.NAN
-
- This method compares a douhle or float to the constant Double.NaN or Float.NaN. You should use
- Double.isNaN(d) or Float.isNaN(f) if a primitive; or d.isNaN() or f.isNaN() if a boxed double, instead.
- ]]>
-
-
-
-
- Method passes double value to BigDecimal Constructor
- Method {1} passes double value to BigDecimal Constructor
-
- This method calls the BigDecimal constructor that takes a double, and passes a literal double constant value. Since
- the use of BigDecimal is to get better precision than double, by passing a double, you only get the precision of double number
- space. To take advantage of the BigDecimal space, pass the number as a string.
- ]]>
-
-
-
-
- Method passes empty string to StringBuffer of StringBuilder constructor
- Method {1} passes empty string to StringBuffer of StringBuilder constructor
-
- This method calls the StringBuffer of StringBuilder constructor passing in a constant empty string ("").
- This is the same as calling the default constructor, but makes the code work harder. Consider passing in a
- default size instead.
- ]]>
-
-
-
-
- Method calls equals on an enum instance
- Method {1} calls equals on an enum instance
-
- This method calls the equals(Object) method on an enum instance. Since enums values are singletons,
- you can use == to safely compare two enum values. In fact, the implementation for Enum.equals does just
- that.
- ]]>
-
-
-
-
- Method uses invalid C++ style null check on Boolean
- Method {1} uses invalid C++ style null check on Boolean
-
- This method attempts to check for null by just refering to the variable name
- as would be done in C++. This ordinarily would be considered a compile error, except the
- variable in question is a Boolean, which does an auto unbox to boolean.
-
- if (b && b.booleanValue())
- should be
- if ((b != null) && b.booleanValue())
-
- ]]>
-
-
-
-
- Method fetches character array just to do the equivalent of the charAt method
- Method {1} fetches character array just to do the equivalent of the charAt method
-
- This method calls the toCharArray method on a String the fetch an array of characters, only
- to retrieve one of those characters by index. It is more performant to just use the charAt method.
-
- ]]>
-
-
-
-
- Method uses a trinary operator to cast a boolean to true or false
- Method {1} uses a trinary operator to cast a boolean to true or false
-
- This method tests the value of a boolean and using a trinary operator to return either true or false.
- The trinary operator is completely unecessary, just use the original boolean value.
- ]]>
-
-
-
-
- Method treats null and normal strings differently than an empty strings
- Method {1} treats null and normal strings differently than an empty strings
-
- This method tests a string, and groups null values with real strings, leaving empty strings as another
- case. This might be perfectly valid, but normally, null strings and empty strings are logically handled the same way,
- and so this test may be flawed.
-
Pattern found is one of the following
-
if ((s == null) || (s.length() > 0))
-- did you mean ((s == null) || (s.length() == 0))?
-
if ((s == null) || (s.length() != 0))
-- did you mean ((s == null) || (s.length() == 0))?
-
if ((s != null) && (s.length() == 0))
-- did you mean ((s != null) && (s.length() > 0))?
- or perhaps ((s == null) || (s.length() == 0))?
-
- ]]>
-
-
-
-
- Method converts StringBuffer or Builder to String just to get it's length
- Method {1} converts StringBuffer or Builder to String just to get it's length
-
- This method calls the toString method on a StringBuffer or StringBuilder only to call length() on the resulting
- string. It is faster, and less memory intensive to just call the length method directly on the StringBuffer or StringBuilder
- itself.
- ]]>
-
-
-
-
- Method assigns a variable in a larger scope then is needed
- Method {1} assigns a variable in a larger scope then is needed
-
- THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD
- This method assigns a value to a variable in an outer scope compared to where the variable is actually used.
- Assuming this evaluation does not have side effects, the assignment can be moved into the inner scope (if block)
- so that its execution time isn't taken up if the if guard is false. Care should be
- taken however that the right hand side of the assignment does not contain side
- effects that are required to happen, or that changes are not made further down that
- will effect the execution of the assignment when done later on.
- ]]>
-
-
-
-
- Class implements interface by relying on unknowing superclass methods
- Class {0} implements interface by relying on unknowing superclass methods
-
- This class declares that it implements an interface, but does so by relying on methods supplied
- by superclasses, even though those superclasses know nothing about the interface in question. If you wish
- to have the child not implement all the methods of the interface, it would probably be better to declare
- the superclass as implementing the interface, and if that class does not provide all the methods, then declare
- that superclass abstract.
- ]]>
-
-
-
-
- Method deletes collection element while iterating
- Method {1} deletes collection element while iterating
-
- This method removes items from a collection using the remove method of the collection, while
- at the same time iterating across the collection. Doing this will invalidate the iterator, and further
- use of it, will cause ConcurrentModificationExceptions to be thrown. To avoid this, the remove
- method of the iterator should be used.
-
- ]]>
-
-
-
-
- Method modifies collection element while iterating
- Method {1} modifies collection element while iterating
-
- This method modifies the contents of a collection using the collection api methods, while
- at the same time iterating across the collection. Doing this will invalidate the iterator, and further
- use of it, will cause ConcurrentModificationExceptions to be thrown.
-
- ]]>
-
-
-
-
- Method builds String array using String Tokenizing
- Method {1} builds String array using String Tokenizing
-
- This method uses a StringTokenizer to split up a String and then walks thru the
- separated elements and builds an array from these enumerated values. It is simpler
- and easier to use the String.split method.
-
PLEASE NOTE: String.split will return an array of 1 element when passed the
- empty string, as opposed to using StringTokenizer which returns false on the first
- hasMoreElements/hasMoreTokens call. So you may need to use
-
- if (s.length() > 0)
- return s.split(";");
- return new String[0];
-
- ]]>
-
-
-
-
- method uses rt.jar class or method that does not exist
- method {1} uses rt.jar class or method that does not exist for the version the class is compiled for
-
- This method calls a method that does not exist, on a class that does not exist in the jdk that
- this class has been compiled for. This can happen if you compile the class specifying the -source and
- -target options, and use a version that is before the version of the compiler's JDK.
- ]]>
-
-
-
-
- method uses simple loop to copy contents of one collection to another
- method {1} uses simple loop to copy contents of one colleciton to another
-
- This method uses a simple for loop to copy the contents of a set, list, map key/value, array or other collection
- to another collection. It is simpler and more straight forward to just call the addAll method of the destination collection
- passing in the source collection. In the case that the source is an array, you can use Array.asList method to massage the array
- into a collection
- ]]>
-
-
-
-
- private method only returns one constant value
- private method {1} only returns one constant value
-
- This private method only returns one constant value. As this method is private,
- it's behavior can't be overridden, and thus the return of a constant value seems dubious.
- Either the method should be changed to return no value, or perhaps another return value
- was expected to be returned in another code path in this method.
- ]]>
-
-
-
-
- method needlessly implements what is default streaming behavior
- method {1} needlessly implements what is default streaming behavior
-
- This method implements the Serializable interface by performing the same operations that
- would be done if this method did not exist. Since this is the case, this method is not needed.
- ]]>
-
-
-
-
- class 'overloads' a method with both instance and static versions
- class {0} 'overloads' a method with both instance and static versions
-
- This class 'overloads' the same method with both an instance and static version. As the use
- of these two models is different, it will be confusing to the users of these methods.
- ]]>
-
-
-
-
- unconstrained method converts checked exception to unchecked
- unconstrained method {1} converts checked exception to unchecked
-
- This method is not constrained by an interface or superclass, but converts a caught checked exception
- to unchecked exception and thrown. It would be more appropriate just throw the checked exception, adding
- the exception to the throws clause of the method.
- ]]>
-
-
-
-
- constrained method converts checked exception to unchecked instead of another allowable checked exception
- constrained method {1} converts checked exception to unchecked instead of another allowable checked exception
-
- This method's exception signature is constrained by an interface of super class to not throw a
- checked exception that was caught. Therefore this exception was converted to an unchecked exception and
- thrown. It would probably be better to throw the closest checked exception allowed, and to annotate
- the new exception with the original exception using the initial cause field.
- ]]>
-
-
-
-
- constrained method converts checked exception to unchecked
- constrained method {1} converts checked exception to unchecked
-
- This method's exception signature is constrained by an interface or super class to not throw
- any checked exceptions. Therefore a caught checked exception was converted to an unchecked exception
- and thrown. However it appears that the class in question is owned by the same author as the constraining
- interface or superclass. Consider changes the signature of this method to include the checked exception.
- ]]>
-
-
-
-
- method returns modified parameter
- method {1} returns modified parameter
-
- This method appears to modify a parameter, and then return this parameter as the
- methods return value. This will be confusing to callers of this method, as it won't be
- apparent that the 'original' passed in parameter will be changed as well. If the purpose
- of this method is to change the parameter, it would be more clear to change the method to
- a have a void return value. If a return type is required due to interface or superclass contract,
- perhaps a clone of the parameter should be made.
- ]]>
-
-
-
-
-
- Inefficient String Buffering
- Synchronized Collection Iterators
- Cyclomatic Complexity
- Overly Concrete Parameters
- List Indexed Iterating
- Unrelated Collection Contents
- Declared Runtime Exception
- Class Envy
- Literal String Comparison
- Partially Constructed Object Access
- Dubious List Collection
- Parallel Lists
- Final Parameters
- Abstract Class Empty Methods
- Manual Array Copy
- Floating Point Loops
- Non Collection Method Use
- Confusing Autoboxed Overloading
- Abnormal Finally Block Return
- Static Method Instance Invocation
- Spurious Thread States
- Needless Autoboxing
- Unnecessary Store Before Return
- Copied Overridden Method
- Array Based Collection
- Orphaned DOM Node
- Abstract Overridden Method
- Custom Built XML
- Bloated Synchronized Block
- Constant List Index
- Sloppy Class Reflection
- Array Wrapped Call By Reference
- Sluggish Gui
- Needless Instance Retrieval
- Double Date comparison
- Suspicious Wait on Concurrent Object
- JDBC Vendor Reliance
- Possible Memory Bloat
- Local Synchronized Collection
- Field Could Be Local
- Non Owned Synchronization
- Non Recycleable Taglib
- Section 508 Compliance Violations
- Use Enum Collections
- SQL In Loop
- Needless Member Collection Synchronization
- Inheritance Type Checking
- Static Array Created in Method
- Possibly Redundant Method Calls
- Use toArray
- Lost Exception Stack Trace
- Use Character Parameterized Method
- Tail Recursion
- Unrelated Return Values
- Possible Incomplete Serialization
- Suspicious Comparator Return Values
- Sillyness Pot Pourri
- Bloated Assignment Scope
- Spoiled Child Interface Implementor
- Deleting While Iterating
- Use String Split
- Suspicious JDK Version Use
- Use Add All
- Method Returns Constant
- Needless Custom Serialization
- Misleading Overload Model
- Exception Softening
- Confusing Function Semantics
-
\ No newline at end of file
diff --git a/src/main/resources/hudson/plugins/violations/types/findbugs/fb-contrib-6.2.1.messages.xml b/src/main/resources/hudson/plugins/violations/types/findbugs/fb-contrib-6.2.1.messages.xml
new file mode 100644
index 0000000..368ef71
--- /dev/null
+++ b/src/main/resources/hudson/plugins/violations/types/findbugs/fb-contrib-6.2.1.messages.xml
@@ -0,0 +1,4945 @@
+
+
+
+
+
+ fb-contrib plugin
+
+ This plugin contains FindBugs detectors from the fb-contrib project
+ ]]>
+
+ http://fb-contrib.sourceforge.net/bugdescriptions.html
+ http://fb-contrib.sourceforge.net/bugdescriptions.html
+
+
+
+
+
+
+ Collects statistics for other detectors
+ ]]>
+
+
+
+
+
+ Collects method calls that may return immutable collections
+ ]]>
+
+
+
+
+
+ Looks for appending strings inside of calls to StringBuffer or StringBuilder append.
+
+ You should use the .append method to append values
+
+ sb.append(a).append(b);
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for use of iterators on synchronized collections built from the java.util.Collections class
+
As the collection in question was built through Collections.synchronizedXXX, an assumption
+ is made that this collection must be multithreaded safe. However, iterator access is used,
+ which is explicitly unsafe. When iterators are to be used, synchronization should be done manually.
+
It is a slow detector.
+ ]]>
+
+
+
+
+
+ Calculates the McCabe Cyclomatic Complexity measure and reports methods that have an
+ excessive value. This report value can be set with system property 'fb-contrib.cc.limit'.
+
It is a slow detector.
+ ]]>
+
+
+
+
+
+ Looks for parameters that are defined by classes, but where the method only use methods defined by an
+ implemented interface or super class of that class. Relying on concrete classes in public signatures causes cohesion,
+ and makes low impact changes more difficult.
+
It is a slow detector.
+ ]]>
+
+
+
+
+
+ Looks for for loops that iterate over a java.util.List using an integer index, and get,
+ rather than using an Iterator. An iterator may perform better depending on List implementation,
+ but more importantly will allow the code to be converted to other collection types.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for collections or arrays that hold objects that are unrelated through class or
+ interface inheritance other than java.lang.Object. Doing so makes for brittle code,
+ relying either on positional correspondence for type, or a reliance on instanceof to
+ determine type. A better design usually can be had by creating a separate class,
+ which defines the different types required, and add an instance of that class to the
+ collection, or array.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that declare RuntimeExceptions in their throws clause. While doing
+ so is not illegal, it may represent a misunderstanding as to the exception in question.
+ If a RuntimeException is declared, it implies that this exception type is expected to happen,
+ which if true should be handled in code, and not propagated.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD
+
Looks for methods that use a high percentage of methods from another class over its own
+ methods. When this is the case, it is often better to implement this method in that other class,
+ by refactoring the class to accept parameters it needs from the source class.
+ The reporting percentage can be set with system property 'fb-contrib.ce.percent'.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that compare strings against literal strings, where the literal string
+ is passed as the parameter. If the .equals or .compareTo is called on the literal itself, passing
+ the variable as the parameter, you avoid the possibility of a NullPointerException.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for constructors of non final classes that make method calls to non final methods.
+ As these methods could be overridden, the overridden method will be accessing an object that
+ is only partially constructed, perhaps causing problems. Making these called methods final is
+ an easy fix, where possible.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for fields that are implementations of java.util.List, but that are used in a set-like fashion.
+ Since lookup type operations are performed using a linear search for Lists, the performance for large
+ Lists will be poor. Consideration should be made as to whether these fields should be sets. In the
+ case that order is important, consider using LinkedHashSet.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that maintain two or more lists or arrays associated one-for-one through the same index
+ to hold two or more pieces of related information. It would be better to create a new class that holds
+ all of these pieces of information, and place instances of this class in one list. Or if the two list are
+ related in key/value fashion, then use a map instead.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that correctly do not write to a parameter. To help document this, and to perhaps
+ help the JVM optimize the invocation of this method, you should consider defining these parameters
+ as final.
+
+
Performance gains are debatable as "the final keyword does not appear in the class file for
+ local variables and parameters, thus it cannot impact the runtime performance. It's only use
+ is to clarify the coders intent that the variable not be changed (which many consider dubious
+ reason for its usage), and dealing with anonymous inner classes." - http://stackoverflow.com/a/266981/1447621
+
+
It is a slow detector.
+ ]]>
+
+
+
+
+
+ Looks for abstract classes that define empty methods or methods that simply throw an
+ exception. Since this is an abstract class, it may be cleaner to simple define this method
+ as abstract, so that correct subclass behavior is enforced.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that copy data from one array to another using a loop. It is
+ better performing to use System.arraycopy to do such copying as this is a native method.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that use floating point indexes for loops. Since floating point
+ math is imprecise, rounding errors will occur each time through the loop causing
+ hard to find problems. It is usually better to use integer indexing, and calculating
+ the correct floating point value from the index.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for method calls to collection classes where the method is not defined by the Collections
+ interface, and an equivalent method exists in the interface. Examples include:
+
+
Old Method
New Method
+
Hashtable.contains
Map.containsValue
+
Hashtable.elements
Map.elements
+
Hashtable.keys
Map.keySet
+
Vector.addElement
List.add
+
Vector.elementAt
List.get
+
Vector.insertElementAt
List.add
+
Vector.removeAllElements
List.clear
+
Vector.removeElement
List.remove
+
Vector.removeElementAt
List.remove
+
Vector.setElementAt
List.set
+
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that have the same signature, except where one uses a
+ Character parameter, and the other uses an int, long, float, double parameter.
+ Since autoboxing is available in 1.5 one might assume that
+
+ test('a')
+
+ would map to
+
+ public void test(Character c)
+
+ but instead maps to one that takes an int, long, float or double, such as
+
+ public void test(int i)
+
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that have finally blocks that return values
+ or throw exceptions. This code will swallow normal program flow and
+ hide real program logic.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that make static method calls using an instance reference.
+ For documentation purposes, it is better to call the method using the class name.
+ This may represent a change in definition that should be noticed.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that call wait, notify or notifyAll on an instance of a
+ java.lang.Thread. Since the internal workings of the threads is to synchronize on the
+ thread itself, introducing client calls will confuse the thread state of the object
+ in question, and will cause spurious thread state changes, either waking threads up
+ when not intended, or removing the thread from the runnable state.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that pass a primitive wrapper class object to the
+ same class' Constructor. Patterns found are:
+
+
new Boolean(Boolean)
+
new Byte(Byte)
+
new Character(Character)
+
new Short(Short)
+
new Integer(Integer)
+
new Long(Long)
+
new Float(Float)
+
new Double(Double)
+
+ Since primitive wrapper classes are immutable this is needless garbage being created. Just
+ use the original reference.
+
+
It also looks for calls to BoxedClass.valueOf(x) where X is already a Boxed class
+
It also looks for calls to BoxedClass.valueOf(myString).boxedValue(), when instead it is
+ simpler to use BoxedClass.parseBoxed(myString)
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that store the return result in a local variable and
+ then immediately return that local variable. It is simpler to just return
+ the method (or assignment) result directly.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that are direct copies of the implementation in the super class.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that use arrays for items in the keyset of a map, or as
+ an element of a set, or in a list when using the contains method. Since arrays
+ do not, and cannot define an equals method, reference equality is used for these
+ collections, which is probably not desired. If it is, consider using the IdentityHashMap
+ class when using Maps in this case, to better document your intentions.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that create DOM nodes but do not add them to any DOM Document.
+ Either the node was needed to be added to the tree, or the node likely was created in error.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that are declared as abstract that override concrete methods in a
+ super class. Doing this casts away the implementation of the super class, and breaks
+ the contract as set forth by the parent class.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that build XML based strings by concatenation strings
+ and custom values together. Doing so makes brittle code, that is difficult to
+ modify, validate and understand. It is cleaner to create external XML files that are
+ transformed at runtime, using parameters set through Transformer.setParameter.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that are implemented using synchronized blocks, but are overly
+ synchronized because the beginning of the block only accesses local variables,
+ and not member variables, or this.
+
It is a slow detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that access arrays or classes that implement java.util.List
+ using a constant integer for the index. This is often a typo intended to be a loop
+ variable, but if specific indices mean certain things, perhaps a first class object
+ would be a better choice for a container, on even a map with informative key names
+ would be better.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that use Class.forName("XXX") to load a class object
+ for a class that is already referenced by this class. It is simpler to just use
+ XXX.class, and doing so protects the integrity of this code from such transformations
+ as obfuscation. Use of Class.forName should only be used when the class in question
+ isn't already statically bound to this context.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that use an array of length one to pass a variable to achieve call
+ by pointer ala C++. It is better to define a proper return class type that holds all
+ the relevant information retrieved from the called method.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that implement AWT or Swing listeners and perform time
+ consuming operations. Doing these operations in the GUI thread will cause the
+ interface to appear sluggish and non-responsive to the user. It is better to
+ use a separate thread to do the time consuming work so that the user
+ has a better experience.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that call a method to retrieve a reference to an object,
+ to use to load a constant. It is simpler and more performant to access the
+ static variable directly from the class itself.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for inefficient comparison of Date objects using two comparisons when one would do.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for calls to the wait method on mutexes defined in the java.util.concurrent
+ package where it is likely that await was intended.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for uses of JDBC vendor specific classes and methods making the database
+ access code non portable.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that maintain collections or StringBuffer/StringBuilders in
+ static member variables, and that do not appear to provide a way to clear or remove
+ items from these members. Such class fields are likely causes of memory bloat.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for allocations of synchronized collections that are stored in local
+ variables, and never stored in fields or returned from methods. As local variables
+ are by definition thread safe, using synchronized collections in this context
+ makes no sense.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that define fields that are used in a locals only fashion,
+ specifically private fields that are accessed first in each method with a
+ store vs. a load.
+
It is a slow detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that synchronize on variables that are not owned by the
+ current class. Doing this causes confusion when two classes use the same variable
+ for their own synchronization purposes. For cleanest separation of interests, only
+ synchronize on private fields of the class. Note that 'this' is not owned by
+ the current class and synchronization on 'this' should be avoided as well.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for tag libraries that are not recycleable because backing members
+ of taglib attributes are set in areas besides the setter method for the attribute.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for violation of Section 508, Accessibility for People with disabilities Act.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for use of sets and maps using enums. It is more efficient to use EnumSet or EnumMap.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for the execution of SQL queries inside a loop. This pattern tends to be inefficient,
+ and often can be improved upon, by collecting all the keys needed for the query and issuing just
+ one query using an in clause with all the keys for all the queries previously needed in the loop.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that define private synchronized collections as static or instance
+ members, that are only altered in a static initializer or constructor. Since the multithreaded
+ use of this collection is read-only, the use of synchronization is unnecessary.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for if/else blocks where a series of them use instanceof on the same
+ variable to determine what to do. If these classes are related by inheritance,
+ this often is better handled through calling a single overridden method.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for creation of arrays in methods using constant values. These arrays
+ will need to be recreated each time the method is called. These arrays should probably
+ be defined as static fields, instead.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for calls of the same method on the same object when that object hasn't changed.
+ This often is redundant, and the second call can be removed, or combined.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for code that builds an array of values from a collection, by manually looping
+ over the elements of the collection, and adding them to the array. It is simpler and
+ cleaner to use mycollection.toArray(new type[mycollection.size()]).
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that catch exceptions, and then throw a different exception
+ without embedding the original exception in the thrown one. Doing so, hides the real
+ source of the exception, making debugging and fixing these problems difficult.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that pass single character string constants as parameters to
+ methods that alternatively have an overridden method that accepts a character instead.
+ It is easier for the method to handle a single character than a String.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that make a recursive call to itself as the last statement in the
+ method. This tail recursion could be converted into a simple loop which would improve
+ the performance and stack requirements.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that are defined to return Object, and return different types of
+ objects based on different code paths. If this method is not based on an interface or
+ superclass, it is suggested to change the return type to a type that would accommodate
+ all kinds of return types.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that don't handle serialization of parent class member fields
+ when the class in question is serializable but is derived from a non serializable
+ classes.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for class that implement Comparator or Comparable, and whose compare or compareTo
+ methods return constant values only, but that don't represent the three possible choice
+ (a negative number, 0, and a positive number).
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for a potpourri of small problems that do not fit into a common pattern.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD
+
Looks for assignments to variables in a scope larger than its use. As long as the evaluation of the assignment
+ does not have side effects, the assignment can be moved into the inner scope where it is used.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that implement interfaces by relying on methods being
+ implemented in superclasses, even though the superclass knows nothing about
+ the interface being implemented by the child.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for deletion of items from a collection using the remove method
+ of the collection at the same time that the collection is being iterated on. If
+ this occurs the iterator will become invalid and throw a ConcurrentModificationException.
+ Instead, the remove should be called on the iterator itself.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for code that builds an array by using a StringTokenizer to break up
+ a string and place individual elements into an array. It is simpler to use
+ String.split instead.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for calls to classes and methods that do not exist in the JDK for which this class is
+ compiled. This can happen if you specify the -source and -target options of the javac compiler, and
+ specify a target that is less than the JDK version of the javac compiler.
+
It is a slow detector.
+ ]]>
+
+
+
+
+
+ Looks for loops that transfer the contents of one collection to another. These collection sources might
+ be local variables or member fields, including sets, maps key/values, lists, or arrays. It is simpler to
+ just use the addAll method of the collection class. In the case where the source is an array, you can use
+ Arrays.asList(array), and use that as the source to addAll.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for private or static methods that only return one constant value. Since there is no
+ chance for derived classes overriding this behavior, the return of a constant value
+ seems dubious.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that implement the Serializable interface and implement the
+ standard readObject and writeObject methods by simply deferring to the Stream
+ parameter's defaultReadObject or defaultWriteObject and nothing else. As this is the
+ built in behavior, these methods are not needed.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that define both static and instance methods with the same name.
+ As each type represents a different use model, it doesn't make sense that this name
+ would be overloaded, and will confuse users of the class.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that catch checked exceptions, and throw unchecked
+ exceptions in their place. There are several levels of concern. Least
+ concerning are methods constrained by interface or super class contracts
+ not to throw checked exceptions but appear owned by the same author. Next
+ are methods constrained by interface or super class contracts and throw other
+ types of checked exceptions. Most egregious are methods not constrained by any interface
+ or superclass contract.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that return a parameter after modifying that parameter.
+ Doing this will confuse the user of this method, as it will be assumed that the
+ passed in argument is different than the output, or at least won't be changed.
+ If the purpose of this method is just to modify the parameter, this method should
+ probably be changed to have a void return type. If you must return a variable, perhaps
+ a clone of the parameter should be returned.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for junit test case methods that use assertions with odd parameters.
+ Including in this is:
+
+
Passing a constant as the second (actual) parameter
+
not using the three parameter version of asserts for doubles
+
Passing true or false as the first parameter instead of using assertTrue, or assertFalse
+
Using the assert keyword
+
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for implementations of clone where an assignment is made to a field of the
+ source object. It is likely that that store should have occurred on the cloned object, as
+ the clone operation is almost always considered read only.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for exceptions that are thrown with static strings as messages. Using static strings
+ doesn't differentiate one use of this method versus another, and so it may be difficult
+ to determine how this exception occurred without showing context.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for code that fetches a complex object from an HttpSession attribute, modifies the
+ object, but does not call setAttribute again on this object. This will not inform the application server
+ that this object has changed, and thus will not correctly replicate these changes across the cluster.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for odd patterns of use of Logger classes from either log4j, SLF4J or Commons Logging.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that rely on internal classes in the various APIs or libraries. As these
+ classes are not officially released from the API vendor, they are subject to change or removal, and thus,
+ should not be counted on.
+ Packages that shouldn't be used are:
+
+
com.sun.xxx
+
org.apache.xerces.xxx
+
org.apache.xalan.xxx
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for sets or keySets of maps that contain other collections. As typically collections calculate
+ their hashCode, equals and compareTo methods by iterating the collection and evaluating the same function
+ on each item in the collection, this can be costly from a performance point of view.
+
In addition, using a set, or keySet of a map, infers that you will be looking for items based on
+ the value of a collection, which seems dubious at best.
+
Finally, as collections are often modified, this may cause problems if the collection is modified,
+ thus changing hashCodes, etc, while the collection is in the set.
+
If you wish to keep a collection of collections, the outer collection should probably be a list
+ to avoid these problems.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for constructors, static methods and private methods that declare that they throw
+ checked exceptions that the actual code never throws. Since these methods can't be overridden,
+ there is no reason to add these exceptions to the method declaration.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for allocations of objects, and then immediately checking to see if the
+ object is null, or non null. As the new operator is guaranteed to either succeed, or throw
+ an exception, this null check is useless, and denotes a misunderstanding as to how
+ the JVM works. You can remove this guard.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that appear to implement the old style type safe enum pattern
+ that was used before Java added Enum support to the language. Since this class is
+ compiled with Java 1.5 or later, it would be simpler to just use Java enums.
+
It is a fast detector.
+ ]]>
+
+
+
+
+ experimental="true"
+ Looks for method calls that pass the same value for two separate parameters, where
+ those arguments are not constants. Often this is a cut/paste mistake, but if not, it is
+ confusing why you would pass the same value for two arguments.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that are declared to return a Boolean, but return a null
+ value. As this now allows the method to return 3 values, the use of Boolean is
+ dubious. It would be better to just define a new enumeration with three values,
+ and return that.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that return arrays that are allocated but not initialized
+ in this method. While it's possible that the calling method will do the work of
+ initializing the array, it is not a usual pattern, and it is suspected that this array
+ was just forgotten to be initialized.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that perform algorithmic operations on Strings that are returned
+ from a toString() method. As toString should only be used for debug/trace purposes, it
+ shouldn't be used for algorithm use.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that use the same name with different casing to access objects in HttpRequest parameters
+ and attributes. As these parameter names are case-sensitive this will lead to confusion.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for manual casts of objects that are more specific than needed as the value is assigned
+ to a class or interface higher up in the inheritance chain. You only need to cast to that class
+ or interface.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for non derivable methods that declare parameters and then cast those
+ parameters to more specific types in the method. This is misleading and dangerous
+ as you are not documenting through parameter types what is necessary for these
+ parameters to function correctly.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that break the fundamental rule of equivalence, which is
+ symmetry. If a equals b, then b equals a. While it is usually wrong to allow
+ equals to compare different types, at the very least you should make sure that
+ each class knows about each other and is able to compare themselves with each other.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Finds contravariant array assignments. Since arrays are mutable data structures, their use
+ must be restricted to covariant or invariant usage.
+
+
+ class A {}
+ class B extends A {}
+
+ B[] b = new B[2];
+ A[] a = b;
+ a[0] = new A(); // results in ArrayStoreException (Runtime)
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for fields in serializable classes that are defined as both final and
+ transient. As a transient field is not initialized when streamed, and is not
+ initialized in a constructor, it will remain null because it is defined final.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for code that checks to see if a field or local variable is not null,
+ before entering a code block either an if, or while statement, and then reassigns that
+ field or local variable. It is likely that guard should have been to see if that
+ field or local variable is null, not, not null.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for calls to more pointless or deprecated methods.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for reflective calls on methods that are found in the class java.lang.Object.
+ As these methods are always available, there is no reason to use reflection to call them.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for java.util.Properties use where values other than String
+ are placed in the properties object. As the Properties object was intended to be a
+ String to String only collection, putting other types in the Properties object is
+ incorrect, and takes advantage of a poor design decision by the original Properties class
+ designers to derive from Hashtable, rather than using aggregation.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for allocations of objects using the default constructor in a loop, where
+ the object allocated is never assigned to any object that is used outside the loop.
+ It is possible that this allocation can be done outside the loop to avoid excessive garbage.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for allocations and initializations of Java collections, but that are never
+ read from or accessed to gain information. This represents a collection of no use, and most probably
+ can be removed. It is similar to a dead local store.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for definitions of methods that have an array as the last parameter.
+ Since this class is compiled with Java 1.5 or better, it would be more flexible for clients of this
+ method to define this parameter as a vararg parameter.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for code that serializes objects that are non-static inner
+ classes of other classes. Since there is a reference to the containing class, this class will be serialized as well.
+ It is often the case that this is not what is wanted, and will cause much more data to be serialized
+ than is necessary.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for object creation where the object isn't assigned to any variable or
+ field. This implies that the class operates through side effects in the constructor, which makes
+ for difficult to maintain code.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for Java bean getter-setter use where the value of a property is set
+ with the value retrieved from the same bean's correllary getter, like this:
+
+ person.setAge(person.getAge());
+
+
Typically this is a copy paste typo.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for creation of java.awt.Graphics object that do not have the
+ .dispose() method called on them when finished. These objects will be cleaned up by
+ the Garbage collector, bug given the likelihood that large numbers of these objects can
+ be created in a short period of time, it is better to dispose them as soon as possible.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for two or more try catch blocks that are consecutive
+ and catch the same kind of exception, and each catch block mandatorily throws
+ the same exception. These two catch blocks can and should be made into one
+ catch block to simply the code.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for uses for Commons-lang EqualsBuilder where the
+ result of equals() is returned instead of calling the method isEquals().
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for uses for Commons-lang HashCodeBuilder where the
+ result of hashCode() is returned instead of calling the method toHashCode().
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for uses for Commons-lang ToStringBuilder where the
+ result of toString() is returned without an intermediate invocation of toString().
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ In a JVM, two classes are the same class (and consequently the same type) if
+ they are loaded by the same class loader, and they have the same fully
+ qualified name [JVMSpec 1999].
+
+ Comparing class name ignores the class loader.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Detects use of Backport Utils concurrent classes. Updated/Efficient version of these
+ classes are available in versions of the JDK 5.0 and higher, and these
+ classes should only be used if you are targeting JDK 1.4 and lower.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that implement clone() that do not specialize the return value, and do
+ not swallow CloneNotSupportedException. Not doing so makes the clone method not as simple to use,
+ and should be harmless to do so.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for calls to Arrays.asList where the parameter is a primitive array.
+ This does not produce a list that holds the primitive boxed values, but a list of
+ one item, the array itself.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that create collections using the default constructor,
+ even though the number of elements that will be placed in the collection is known
+ a priori, and thus could be pre-allocated. Not doing so just causes more intermediate
+ reallocations which is unnecessary.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that declare method level template parameter(s) that are not bound to any of the
+ method's parameters, and thus is not adding any validation/type safety to the method, and is
+ just confusing.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for common methods that are non mutating where the return value is ignored. As these methods
+ do not change the object they are called on, calling these methods is pointless. They can be removed.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for questionable load/stores to array elements.
+
+
+ Looks for accesses to array elements using literal values that are known to be outside the bounds of the array.
+ This mistake will cause an ArrayIndexOutOfBoundsException to occur at runtime.
+
+ Looks for stores to array elements where the array itself appears to have not been allocated.
+
+
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for method calls that take a parameter value that does not match one of the expected
+ values for that parameter. It is likely this parameter value should really be an enum, but predates
+ the addition of enums to Java. Passing an invalid value will likely cause problems in the execution of
+ the method.
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for fields or local variables that are collections but the names have a different type
+ of collection in the name. This is confusing, and is probably a left over from a type change, such as
+
+
List mySet;
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for fields defined with simple types, (int, String, etc) that are used like an enum. Specifically fields that are
+ only assigned a set of constant values. This variable probably should be redefined as an enum.
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for private or static methods that have parameters that aren't used. These parameters
+ can be removed, assuming the method isn't used through reflection.
+
It is fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks circular dependencies among classes.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for code that attempts to modify a collection that is or may be
+ defined as immutable. Doing so will cause exceptions at runtime.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Three detectors for hanging ExecutorServices, that is, ExecutorServices that never get a call to shutdown, which
+ can potentially cause the JVM to not exit.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ The HttpRequests from the Apache HttpComponents have some little-known quirks about them.
+ This is a set of detectors that helps guard against resource starvation.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ This detector looks for methods that are longer than 8000 bytes. Methods this
+ long are automatically disqualified by the JIT for compilation and will always be
+ emulated. Consider breaking this method up to avoid this, if performance is important.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that perform arithmetic operations on values representing time
+ where the time unit is incompatible, ie adding a millisecond value to a nanosecond value.
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for manual specification of String encoding using String constants where either
+ a StandardCharset could be used (JDK7) or where the encoding is not recognized with the
+ current JDK.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for complex if expressions made up of multiple conditions joined by OR, where the same
+ local variable is compared to a static value. When the number of conditions grow it is much cleaner
+ to build a static set of the possible values, and use the contains method on that set. This will
+ shorten the code, and make it more self documenting.
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that are declared more permissively than the code is using. For instance, declaring
+ a method public, when it could just be declared private. Having methods have more permissive access than they
+ need to have limits your ability to make observations about these methods, like parameter usage,
+ refactorability, and derivability. This detector will not report on methods that are never called in
+ the case this method is an API like method intended to be called by client code. If this method is
+ also called through reflection, this detector may erroneous report it.
+
It is a moderately fast detector.
+ ]]>
+
+
+
+
+
+ Looks for classes that store fields that are Strings that impersonate instances of classes, or collections that are
+ fields that hold Strings that impersonate a class. Examples of String impersonating are storing:
+
+
the result of a toString call
+
Strings build from parsing or building strings from other objects, such as "1,2,3,4" or "Project:3"
+
+ By using Strings you are throwing away type-safety, and making it difficult to reason about what the values of variables
+ in use are. If a String has multiple parts to it, it probably belongs as a first class Class.
+
+
It is a fast detector.
+ ]]>
+
+
+
+
+
+ Looks for methods that assign a value to a variable in an if equals conditional in a loop, but does not break after doing so.
+ Since equality would seem to be a one time event, continuing with the loop seems pointless, and a break statement in the if statement
+ seems like it should be added.
+
It is a fast detector
+ ]]>
+
+
+
+
+
+ Looks for methods that use the File api on resources retrieved from URLs where the URL in question isn't from a file protocol.
+ In the case of classpath resources, this will work if the code is executed from directories, but fail using jars.
+ If using resources, then use URL.openStream() method instead of File apis.
+
It is a fast detector
+ ]]>
+
+
+
+
+
+
+
+
+
+
+ Method passes simple concatenating string in StringBuffer or StringBuilder append
+ Method {1} passes simple concatenating string in StringBuffer or StringBuilder append
+
+ This method uses StringBuffer or StringBuilder's append method to concatenate strings. However, it passes the result
+ of doing a simple String concatenation to one of these append calls, thus removing any performance gains
+ of using the StringBuffer or StringBuilder class.
+
+
+ Java will implicitly use StringBuilders, which can make this hard to detect or fix. For example,
+
+ StringBuilder sb = new StringBuilder();
+ for (Map.Entry e : map.entrySet()) {
+ sb.append(e.getKey() + e.getValue()); //bug detected here
+ }
+
+
+ gets automatically turned into something like:
+
+ StringBuilder sb = new StringBuilder();
+ for (Map.Entry e : map.entrySet()) {
+ StringBuilder tempBuilder = new StringBuilder();
+ tempBuilder.append(e.getKey());
+ tempBuilder.append(e.getValue());
+ sb.append(tempBuilder.toString()); //this isn't too efficient
+ }
+
+
+ which involves a temporary StringBuilder, which is completely unnecessary. To prevent this from happening, simply do:
+
+
+ StringBuilder sb = new StringBuilder();
+ for (Map.Entry e : map.entrySet()) {
+ sb.append(e.getKey());
+ sb.append(e.getValue());
+ }
+
+
+ ]]>
+
+
+
+
+ Method concatenates an empty string to effect type conversion
+ Method {1} concatenates an empty string to effect type conversion
+
+ This method concatenates an empty string with a literal value, in order to convert
+ the literal value into a string. It is more efficient to use String.valueOf() to do the same
+ thing as you do not incur the cost of creating a StringBuffer/Builder and calling methods on it
+ to accomplish this.
+ ]]>
+
+
+
+
+ Method concatenates the result of a toString() call
+ Method {1} concatenates the result of a toString() call
+
+ This method concatenates the output of a toString() call into a StringBuffer or StringBuilder.
+ It is simpler just to pass the object you want to append to the append call, as that form
+ does not suffer the potential for NullPointerExceptions, and is easier to read.
+
+
+ Keep in mind that Java compiles simple String concatenation to use StringBuilders, so you may see this bug even when you don't use StringBuilders explicitly.
+
+
+
+ Instead of:
+
+ StringBuilder builder = ...
+ builder.append(someObj.toString());
+ ...
+ System.out.println("Problem with the object :" + someObj.toString());
+
+ just do:
+
+ StringBuilder builder = ...
+ builder.append(someObj);
+ ...
+ System.out.println("Problem with the object :" + someObj);
+
+ to avoid the possibility of NullPointerExceptions when someObj is null.
+
+ ]]>
+
+
+
+
+ Method creates iterators on synchronized collections
+ Method {1} creates iterators on synchronized collections
+
+ This method uses a synchronized collection, built from Collections.synchronizedXXXX, but accesses it
+ through an iterator. Since an iterator is by definition, multithreaded unsafe, this is a conflict in
+ concept. When using iterators, you should do the synchronization manually.
+ ]]>
+
+
+
+
+ Method is excessively complex
+ Method {1} is excessively complex, with a cyclomatic complexity of {3}
+
+ This method has a high cyclomatic complexity figure, which calculates the number of branch
+ points. It is likely difficult to test, and is brittle to change. Consider refactoring this
+ method into several to reduce the risk.
+ ]]>
+
+
+
+
+ Method needlessly defines parameter with concrete classes
+ {3}
+
+ This method uses concrete classes for parameters when only methods defined in an implemented
+ interface or super class are used. Consider increasing the abstraction of the interface to
+ make low impact changes easier to accomplish in the future.
+
+
Take the following example:
+
+ private void appendToList(ArrayList list) {
+ if (list.size() < 100) {
+ list.add("Foo");
+ }
+ }
+
+
+ The parameter list is currently defined as an ArrayList, which is a concrete implementation of the List interface.
+ Specifying ArrayList is unnecessary here, because we aren't using any ArrayList-specific methods (like ensureCapacity() or trimToSize()).
+ Instead of using the concrete definition, it is better to do something like:
+
+ private void appendToList(List list) {
+ ...
+
+ If the design ever changes, e.g. a LinkedList is used instead, this code won't have to change.
+
+
+
+
IDEs tend to have tools to help generalize parameters. For example, in Eclipse, the refactoring tool Generalize Declared Type helps find an appropriate level of concreteness.
+ ]]>
+
+
+
+
+ Method uses integer based for loops to iterate over a List
+ Method {1} uses integer based for loops to iterate over a List
+
+ This method uses an integer based for loop to iterate over a java.util.List, by calling
+ List.get(i) each time through the loop. The integer is not used for other reasons. It is better
+ to use an Iterator instead, as depending on List implementation, iterators can perform better,
+ and they also allow for exchanging of other collection types without issue.
+ ]]>
+
+
+
+
+ Method adds unrelated types to collection or array
+ Method {1} adds unrelated types to collection or array
+
+ This method adds unrelated objects to a collection or array, requiring careful and brittle
+ data access to that collection. Create a separate class with properties needed, and add
+ an instance of this class to the collection or array, if possible.
+ ]]>
+
+
+
+
+ Method declares RuntimeException in throws clause
+ Method {1} declares RuntimeException in throws clause
+
+ This method declares a RuntimeException derived class in its throws clause.
+ This may indicate a misunderstanding as to how unchecked exceptions are handled.
+ If is felt that a RuntimeException is so prevalent that it should be declared, it
+ is probably a better idea to prevent the occurrence in code.
+ ]]>
+
+
+
+
+ Method excessively uses methods of another class
+ Method {1} excessively uses methods of another class
+
+ THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD
+
This method makes extensive use of methods from another class over methods of its own
+ class. Typically this means that the functionality that is accomplished by this method
+ most likely belongs with the class that is being used so liberally. Consider refactoring this
+ method to be contained in that class, and to accept all the parameters needed in the method signature.
+ ]]>
+
+
+
+
+ Method makes literal string comparisons passing the literal as an argument
+ Method {1} makes literal string comparisons passing the literal as an argument
+
+ This line is in the form of
+ String str = ...
+ str.equals("someOtherString");
+ //or
+ str.compareTo("someOtherString");
+
A NullPointerException may occur if the String variable str is null. If instead the code was restructured to
+ String str = ...
+ "someOtherString".equals(str);
+ //or
+ "someOtherString".compareTo(str);
+ that is, call equals() or compareTo() on the string literal, passing the
+ variable as an argument, this exception could never happen as both equals() and
+ compareTo() check for null.
+ ]]>
+
+
+
+
+ Constructor makes call to non-final method
+ Constructor {1} makes call to non-final method
+
+ This constructor makes a call to a non-final method. Since this method can be overridden, a subclasses
+ implementation will be executing against an object that has not been initialized at the subclass level.
+ You should mark all methods called from the constructor as final to avoid this problem.
+ ]]>
+
+
+
+
+ Class defines List based fields but uses them like Sets
+ Class {0} defines List based fields but uses them like Sets
+
+ This class defines a field based on java.util.List, but uses it to some extent like a Set. Since
+ lookup type operations are performed using a linear search for Lists, the performance for large
+ Lists will be poor. Consider changing this fields implementation to a set based one. If order of
+ iteration is important to maintain insert order, perhaps consider a LinkedHashSet.
+ ]]>
+
+
+
+
+ Class defines two or more one for one associated lists or arrays
+ Class {0} defines two or more one for one associated lists or arrays
+
+ This class appears to maintain two or more lists or arrays whose contents are related in a parallel way. That is,
+ you have something like:
+
+ List words = new ArrayList();
+ List wordCounts = new ArrayList();
+
+ where the elements of the list at index 0 are related, the elements at index 1 are related and so on.
+
+ Consider creating a separate class to hold all the related
+ pieces of information, and adding instances of this class to just one list or array, or if just two values, use
+ a Map to associate one value with the other like:
+
+ private class WordAndCount{public String word; public int count}
+ List wordsAndCounts = new ArrayList();
+
+ //or, for just two elements
+ Map wordCounts = new HashMap();
+
+
+
+ ]]>
+
+
+
+
+ Method does not define a parameter as final, but could
+ Method {1} does not define one or more parameters as final, but could
+
+ This method does not write to a parameter. To help document this, and to perhaps
+ help the JVM optimize the invocation of this method, you should consider defining these parameters
+ as final.
+
+
Performance gains are debatable as "the final keyword does not appear in the class file for
+ local variables and parameters, thus it cannot impact the runtime performance. It's only use
+ is to clarify the coders intent that the variable not be changed (which many consider dubious
+ reason for its usage), and dealing with anonymous inner classes." - http://stackoverflow.com/a/266981/1447621
+ ]]>
+
+
+
+
+ Empty method could be declared abstract
+ Empty method {1} could be declared abstract
+
+ This method is empty or merely throws an exception. Since the class it is defined in is
+ abstract, it may be more correct to define this method as abstract instead, so that proper
+ subclass behavior is enforced.
+ ]]>
+
+
+
+
+ Method copies arrays manually
+ Method {1} copies arrays manually
+
+ This method copies data from one array to another manually using a loop.
+ It is much better performing to use System.arraycopy as this method is native.
+ ]]>
+
+
+
+
+ Method uses floating point indexed loops
+ Method {1} uses floating point indexed loops
+
+ This method uses floating point variables to index a loop. Since floating point
+ math is imprecise, rounding errors will accumulate over time each time the loop is
+ executed. It is usually better to use integer indexing, and calculate the new value
+ of the floating point number at the top of the loop body.
+ ]]>
+
+
+
+
+ Method uses old non collections interface methods
+ Method {1} uses old non collections interface methods
+
+ This method makes calls to collection classes where the method is not defined by the Collections
+ interface, and an equivalent method exists in the interface. By using the new methods,
+ you can define this object by the Collections interface and allow better decoupling.
+ ]]>
+
+
+
+
+ Class defines methods which confuse Character with int parameters
+ Class {0} defines methods which confuse Character with int parameters
+
+ This class defines two methods that differ only by a parameter being defined
+ as Character vs. int, long, float or double. As autoboxing is present, it may be
+ assumed that a parameter of 'a' would map to the Character version, but does not.
+ ]]>
+
+
+
+
+ Method has abnormal exit from finally block
+ Method {1} has abnormal exit from finally block
+
+ This method returns or throws exceptions from a finally block. This will
+ mask real program logic in the try block, and short-circuit normal method termination.
+ ]]>
+
+
+
+
+ Method calls static method on instance reference
+ Method {1} calls static method on instance reference
+
+ This method makes a static method call on an instance reference. For
+ reading comprehension of the code is better to call the method on the class,
+ rather than an instance. Perhaps this method's static nature has changed since
+ this code was written, and should be revisited.
+ ]]>
+
+
+
+
+ Method calls wait, notify or notifyAll on a Thread instance
+ Method {1} calls wait, notify or notifyAll on a Thread instance
+
+ This method invokes the methods wait, notify or notifyAll on a Thread instance.
+ Doing so will confuse the internal thread state behavior causing spurious thread
+ wakeups/sleeps because the internal mechanism also uses the thread instance for its
+ notifications.
+ ]]>
+
+
+
+
+ Method passes primitive wrapper to same primitive wrapper constructor
+ Method {1} passes primitive wrapper to same primitive wrapper constructor
+
+ This method passes a wrapped primitive object to the same class's constructor.
+ Since wrapper classes are immutable, you can just use the original object, rather
+ than constructing a new one. This code works because of an abuse of autoboxing.
+ ]]>
+
+
+
+
+ Method passes parsed string to primitive wrapper constructor
+ Method {1} passes parsed string to primitive wrapper constructor
+
+ This method passes a primitive value retrieved from a BoxedPrimitive.parseBoxedPrimitive("1") call to
+ the same class's constructor. It is simpler to just pass the string to the BoxedPrimitives constructor or, better yet, use the static valueOf.
+
Instead of something like:
+
+ Boolean bo = new Boolean(Boolean.parseBoolean("true"));
+ Float f = new Float(Float.parseFloat("1.234"));
+
+ Simply do:
+
+ Boolean bo = new Boolean("true");
+ Float f = new Float("1.234");
+
+ or, to be more memory efficient:
+
+ Boolean bo = Boolean.valueOf("true");
+ Float f = Float.valueOf("1.234");
+
+
+ ]]>
+
+
+
+
+ Method passes primitive wrapper to Wrapper class valueOf method
+ Method {1} passes primitive wrapper to Wrapper class valueOf method
+
+ This method passes a wrapped primitive object to the same class's .valueOf method.
+ Since wrapper classes are immutable, you can just use the original object, rather
+ than calling valueOf to create a new one. This code works because of an abuse of autoboxing.
+ ]]>
+
+
+
+
+ Method converts String to primitive using excessive boxing
+ Method {1} converts String to primitive using excessive boxing
+
+ This method passes a String to a wrapped primitive object's valueOf method, which in turn calls
+ the boxedValue() method to convert to a primitive. When it is desired to convert from a String
+ to a primitive value, it is simpler to use the BoxedPrimitive.parseBoxedPrimitive(String)
+ method.
+
+
Instead of something like:
+
+ public int someMethod(String data) {
+ long l = Long.valueOf(data).longValue();
+ float f = Float.valueOf(data).floatValue();
+ return Integer.valueOf(data); // There is an implicit .intValue() call
+ }
+
+ Simply do:
+
+ public int someMethod(String data) {
+ long l = Long.parseLong(data);
+ float f = Float.parseFloat(data);
+ return Integer.parseInt(data);
+ }
+
+
+
+ ]]>
+
+
+
+
+ Method converts String to boxed primitive using excessive boxing
+ Method {1} converts String to boxed primitive using excessive boxing
+
+ This method passes a String to a wrapped primitive object's parse method, which in turn calls
+ the valueOf() method to convert to a boxed primitive. When it is desired to convert from a String
+ to a boxed primitive object, it is simpler to use the BoxedPrimitive.valueOf(String) method.
+
+
Instead of something like:
+
+ Boolean bo = Boolean.valueOf(Boolean.parseBoolean("true"));
+ Float f = Float.valueOf(Float.parseFloat("1.234"));
+
+ Simply do:
+
+ Boolean bo = Boolean.valueOf("true");
+ Float f = Float.valueOf("1.234");
+
+
+ ]]>
+
+
+
+
+ Method creates Boxed primitive from primitive only to get primitive value
+ Method {1} creates Boxed primitive from primitive only to get primitive value
+
+ This method constructs a Boxed Primitive from a primitive only to call the primitiveValue() method to
+ convert it back to a primitive. Just use the primitive value instead.
+
Instead of something like:
+
+ boolean bo = new Boolean(true).booleanValue();
+ float f = new Float(1.234f).floatValue();
+
+ Simply do:
+
+ boolean bo = true;
+ float f = 1.234f;
+
+
+
+ ]]>
+
+
+
+
+ Method creates Boxed primitive from primitive only to cast to another primitive type
+ Method {1} creates Boxed primitive from primitive only to cast to another primitive type
+
+ This method constructs a Boxed Primitive from a primitive only to call the primitiveValue() method to
+ cast the value to another primitive type. It is simpler to just use casting.
+
Instead of something like:
+
+ double someDouble = ...
+ float f = new Double(someDouble).floatValue();
+
+ int someInt = ...
+ byte b = new Integer(someInt).byteValue();
+
+ Simply do:
+
+ double someDouble = ...
+ float f = (float) someDouble;
+
+ int someInt = ...
+ byte b = (byte)someInt;
+
+
+ ]]>
+
+
+
+
+ Method needlessly boxes a boolean constant
+ Method {1} needlessly boxes a boolean constant
+
+ This method assigns a Boxed boolean constant to a primitive boolean variable, or assigns a primitive boolean
+ constant to a Boxed boolean variable. Use the correct constant for the variable desired. Use
+
+ boolean b = true;
+ boolean b = false;
+
+ or
+
+ Boolean b = Boolean.TRUE;
+ Boolean b = Boolean.FALSE;
+
+
+
+
Be aware that this boxing happens automatically when you might not expect it. For example,
+
+ Map statusMap = ...
+
+ public Boolean someMethod() {
+ statusMap.put("foo", true); //the "true" here is boxed
+ return false; //the "false" here is boxed
+ }
+
+ has two cases of this needless autoboxing. This can be made more efficient by simply substituting
+ in the constant values:
+
+
+ Map statusMap = ...
+
+ public Boolean someMethod() {
+ statusMap.put("foo", Boolean.TRUE);
+ return Boolean.FALSE;
+ }
+
+
+ ]]>
+
+
+
+
+ Method stores return result in local before immediately returning it
+ Method {1} stores return result in local before immediately returning it
+
+ This method stores the return result in a local variable, and then immediately
+ returns the local variable. It would be simpler just to return the value that is
+ assigned to the local variable, directly.
+
+ Instead of the following:
+
+ public float average(int[] arr) {
+ float sum = 0;
+ for (int i = 0; i < arr.length; i++) {
+ sum += arr[i];
+ }
+ float ave = sum / arr.length;
+ return ave;
+ }
+
+ simply change the method to return the result of the division:
+
+ public float average(int[] arr) {
+ float sum = 0;
+ for (int i = 0; i < arr.length; i++) {
+ sum += arr[i];
+ }
+ return sum / arr.length;
+ }
+
+
+ ]]>
+
+
+
+
+ Method is implemented with an exact copy of its superclass's method
+ Method {1} is implemented with an exact copy of its superclass's method
+
+ This method is implemented using an exact copy of its super class method's
+ implementation, which usually means that this method can just be removed.
+ ]]>
+
+
+
+
+ Method uses array as basis of collection
+ Method {1} uses array as basis of collection
+
+ This method passes an array as the key to a Map, element in a Set, or item in a List when
+ the contains method is used on the List. Since arrays do not, and cannot override the equals
+ method, collection inclusion is based on the reference's address, which is probably not desired.
+ In the case that this is a TreeMap or TreeSet, consider passing a Comparator to the map's
+ constructor.
+ ]]>
+
+
+
+
+ Method creates DOM node but doesn't attach it to a document
+ Method {1} creates DOM node but doesn't attach it to a document
+
+ This method creates a DOM node but does not attach it to a DOM document.
+ ]]>
+
+
+
+
+ Abstract method overrides a concrete implementation
+ Abstract method {1} overrides a concrete implementation
+
+ This abstract method is derived from a concrete method implementation. It is highly
+ suspect that the super class method's implementation would be cast away.
+ ]]>
+
+
+
+
+ Method builds XML strings through ad hoc concatenation
+ Method {1} builds XML strings through ad hoc concatenation
+
+ This method generates an XML based string by concatenating together various
+ XML fragments, and variable values. Doing so makes the code difficult to read, modify
+ and validate. It is much more clean to built XML structures in external files that are
+ read in and transformed into the final product, through modification by Transformer.setParameter.
+ ]]>
+
+
+
+
+ Method overly synchronizes a block of code
+ Method {1} overly synchronizes a block of code
+
+ This method implements a synchronized block, but the code found at the beginning
+ of this block only accesses local variables, and not member variables, or this.
+ To be better performance move the code that access local variables only, above the
+ synchronized block, and leave the synchronized block only for field accesses, or access
+ to this object.
+ ]]>
+
+
+
+
+ Method accesses list or array with constant index
+ Method {1} accesses list or array with constant index
+
+ This method accesses an array or list using a constant integer index. Often,
+ this is a typo where a loop variable is intended to be used. If however, specific
+ list indices mean different specific things, then perhaps replacing the list with
+ a first-class object with meaningful accessors would make the code less brittle.
+ ]]>
+
+
+
+
+ Method accesses statically bound class with Class.forName
+ Method {1} accesses statically bound class with Class.forName
+
+ This method accesses the class object of a class that is already statically bound
+ in this context, with Class.forName. Using Class.forName makes reflection more fragile
+ in regards to code transformations such as obfuscation, and is unneeded here, since
+ the class in question is already 'linked' to this class.
+ ]]>
+
+
+
+
+ Method uses 1 element array to simulate call by reference
+ Method {1} uses 1 element array to simulate call by reference
+
+ This method uses a one element array to wrap an object that is to be passed to a method as an argument
+ to simulate call by pointer ala C++. It is better to define a proper return class type that holds all
+ the relevant information retrieved from the called method.
+ ]]>
+
+
+
+
+ Method performs time consuming operation in GUI thread
+ Method {1} performs time consuming operation in GUI thread
+
+ This method implements an AWT or Swing listener and performs time
+ consuming operations. Doing these operations in the GUI thread will cause the
+ interface to appear sluggish and non-responsive to the user. Consider
+ using a separate thread to do the time consuming work so that the user
+ has a better experience.
+ ]]>
+
+
+
+
+ Method retrieves instance to load static member
+ Method {1} retrieves instance to load static member
+
+ This method calls a method to load a reference to an object, and then only
+ uses it to load a static member of that instance's class. It is simpler and
+ more performant to just load the static field from the class itself.
+ ]]>
+
+
+
+
+ Method uses two date comparisons when one would do
+ Method {1} uses two date comparisons when one would do
+
+ This method compares dates with two comparisons, rather than using the reverse comparison.
+ So this pattern
+
+ if ((date1.equals( date2 )) || (date1.after( date2 )))
+
+ could become:
+
+ if (date1.compareTo( date2 ) >= 0)
+
+
+ and
+
+ if ((date1.equals( date2 )) || (date1.before( date2 )))
+
+ could become
+
+ if (date1.compareTo( date2 ) <= 0)
+
+
+ and
+
+ if ((date1.before( date2 )) || (date1.after( date2 )))
+
+ could become
+
+ if (!date1.equals( date2 ))
+
+ ]]>
+
+
+
+
+ Method calls wait when await was probably intended
+ Method {1} calls wait when await was probably intended
+
+ This method calls wait() on a on mutex defined in the java.util.concurrent package.
+ These classes, define await, instead of wait, and it is most likely that await
+ was intended.
+ ]]>
+
+
+
+
+ Method uses JDBC vendor specific classes and methods
+ Method {1} uses JDBC vendor specific classes and methods
+
+ This method uses JDBC vendor specific classes and method to perform database work.
+ This makes the code specific to this vendor, and unable to run on other databases.
+ ]]>
+
+
+
+
+ Potential memory bloat in static field
+ Class {0} defines static field "{1}" which appears to allow memory bloat
+
+ This class defines static fields that are Collections, StringBuffers, or StringBuilders
+ that do not appear to have any way to clear or reduce their size. That is, a collection is defined
+ and has method calls like
+ {add(), append(), offer(), put(), ...}
+ with no method calls to removal methods like
+ {clear(), delete(), pop(), remove(), ...}
+ This means that the collection in question can only ever increase in size, which is
+ a potential cause of memory bloat.
+
+
+ If this collection is a list, set or otherwise of static things (e.g. a List for month names), consider
+ adding all of the elements in a static initializer, which can only be called once:
+
+ private static List monthNames = new ArrayList();
+ static {
+ monthNames.add("January");
+ monthNames.add("February");
+ monthNames.add("March");
+ ...
+ }
+
+
+
+ ]]>
+
+
+
+
+ Field is an instance based ThreadLocal variable
+ Field {1} is an instance based ThreadLocal variable
+
+ This ThreadLocal field is defined as being instance based (not static). As all
+ ThreadLocal variables describe permanent reachability roots so far as the garbage
+ collector is concerned, these variables will never be reclaimed (so long as the Thread lives).
+ Since this ThreadLocal is instanced, you potentially will be creating many non reclaimable
+ variables, even after the owning instance has been reclaimed. It is almost a certainty that
+ you want to use static based ThreadLocal variables.
+ ]]>
+
+
+
+
+ Method creates local variable-based synchronized collection
+ Method {1} creates local variable-based synchronized collection
+
+ This method creates a synchronized collection and store the reference to it
+ in a local variable. As local variables are by definition thread-safe, it seems
+ questionable that this collection needs to be synchronized.
+
+
+
If you are using
consider using
+
java.util.Vector
java.util.ArrayList
+
java.util.Hashtable
java.util.HashMap
+
java.lang.StringBuffer
java.lang.StringBuilder
+
+
+ ]]>
+
+
+
+
+ Class defines fields that are used only as locals
+ Class {0} defines fields that are used only as locals
+
+ This class defines fields that are used in a locals only fashion,
+ specifically private fields or protected fields in final classes that are accessed
+ first in each method with a store vs. a load. This field could be replaced by one
+ or more local variables.
+ ]]>
+
+
+
+
+ Class uses non owned variables to synchronize on
+ Class {0} uses non owned variables to synchronize on
+
+ This method uses a synchronize block where the object that is being synchronized on,
+ is not owned by this current instance. This means that other instances may use this same
+ object for synchronization for its own purposes causing synchronization confusion. It is
+ always cleaner and safer to only synchronize on private fields of this class. Note that 'this'
+ is not owned by the current instance, but is owned by whomever assigns it to a field of its
+ class. Synchronizing on 'this' is also not a good idea.
+ ]]>
+
+
+
+
+ Tag library is not recycleable
+ Tag library {0} is not recycleable
+
+ This tag library class implements an attribute who's associated backing store field
+ is modified at another point in the tag library. In order for a taglibrary to be
+ recycleable, only the container is allowed to change this attribute, through the use
+ of the setXXX method of the taglib. By modifying the value programmatically, the
+ container will not initialize the attribute correctly on reuse.
+ ]]>
+
+
+
+
+ GUI uses absolute layout
+ GUI {0} uses absolute layout
+
+ This class passes null to setLayout, which specifies that components are
+ to be laid out using absolute coordinates. This makes making changes for
+ font sizes, etc, difficult as items will not reposition.
+ ]]>
+
+
+
+
+ JLabel doesn't specify what it's labeling
+ JLabel in method {1} doesn't specify what it's labeling
+
+ This class uses JLabels that do not specify what fields are being labeled.
+ This hampers screen readers from given appropriate feed back to users. Use
+ the JLabel.setLabelFor method to accomplish this.
+ ]]>
+
+
+
+
+ Window sets size manually, and doesn't use pack
+ Window {0} sets size manually, and doesn't use pack
+
+ This class creates a window, and sizes the window using setSize. It is better
+ to handle font size changes to use the pack method.
+ ]]>
+
+
+
+
+ Class extends JComponent but does not implement Accessible interface
+ Class {0} extends JComponent but does not implement Accessible interface
+
+ This class extends the JComponent GUI control but does not implement the Accessibility interface.
+ This makes this control unable to be processed by screen readers, etc, for people with reading/vision
+ difficulties.
+ ]]>
+
+
+
+
+ Method explicitly sets the color of a Component
+ Method {1} Method explicitly sets the color of a Component
+
+ This method sets a Components explicitly foreground or background color which may
+ cause difficulty with people with vision problems from using this application.
+ Colors should be allowed to be set from the operating system.
+ ]]>
+
+
+
+
+ Method passes constant string to title/label of component
+ Method {1} passes constant string to title/label of component
+
+ This method creates a component and passes a string literal to the title or label
+ of the component. As this string will be shown to users, it should be internationalizable
+ through the use of a resource bundle.
+ ]]>
+
+
+
+
+ Method passes appended string to title/label of component
+ Method {1} passes appended string to title/label of component
+
+ This method creates a component and passes a string that was build up from a number of
+ strings through appending multiple strings together. As foreign languages may order phrases
+ differently, this will make translations difficult.
+ ]]>
+
+
+
+
+ Class uses an ordinary set or map with an enum class as the key
+ Class {0} uses an ordinary set or map with an enum class as the key
+
+ This class uses an ordinary set or map collection and uses an enum class as the key type.
+ It is more performant to use the JDK 1.5 EnumSet or EnumMap classes.
+ ]]>
+
+
+
+
+ Method executes SQL queries inside of loops
+ Method {1} executes SQL queries inside of loops
+
+ This method executes SQL queries inside of a loop. This pattern is often inefficient
+ as the number of queries may mushroom in fencepost cases. It is probably more performant
+ to loop over the input and collect the key data needed for the query for all items, and
+ issue one query using an in clause, or similar construct, and then loop over this result
+ set, and fetch all the data at once.
+ ]]>
+
+
+
+
+ Class defines unneeded synchronization on member collection
+ Class {0} defines unneeded synchronization on member collection
+
+ This class defines a private collection member as synchronized. It appears however
+ that this collection isn't only modified in a static initializer, or constructor. As these
+ two areas are guaranteed to be thread safe, defining this collection as synchronized is
+ unnecessary and a potential performance bottleneck.
+ ]]>
+
+
+
+
+ Method uses instanceof on multiple types to arbitrate logic
+ Method {1} uses instanceof on multiple types to arbitrate logic
+
+ This method uses the instanceof operator in a series of if/else statements to
+ differentiate blocks of code based on type. If these types are related by inheritance,
+ it is cleaner to just define a method in the base class, and use overridden methods
+ in these classes.
+ ]]>
+
+
+
+
+ Method creates array using constants
+ Method {1} creates array using constants
+
+ This method creates an array initialized by constants. Each time this method is called
+ this array will be recreated. It would be more performant to define the array as a
+ static field of the class instead.
+ ]]>
+
+
+
+
+ Method appears to call the same method on the same object redundantly
+ Method {1} appears to call the same method on the same object redundantly
+
+ This method makes two consecutive calls to the same method using the same constant
+ parameters, on the same instance without any intervening changes to the objects. If this
+ method does not make changes to the object, which it appears it doesn't, then making
+ two calls is just a waste. These method calls could be combined by assigning the
+ result into a temporary, and using the temporary the second time.
+ ]]>
+
+
+
+
+ Method manually creates array from collection
+ Method {1} manually creates array from collection
+
+ This method manually loops over a collection, pulling each element out and storing
+ it in an array to build an array from the collection. It is easier, and clearer to use
+ the built in collections method toArray. Given a collection 'mycollection' of type T, use
+ mycollection.toArray(new T[mycollection.size()]);
+ ]]>
+
+
+
+
+ Method throws alternative exception from catch block without history
+ Method {1} throws alternative exception from catch block without history
+
+ This method catches an exception, and throws a different exception, without incorporating the
+ original exception. Doing so hides the original source of the exception making debugging and fixing
+ these problems difficult. It is better to use the constructor of this new exception that takes an
+ original exception so that this detail can be passed along to the user.
+ ]]>
+
+
+
+
+ Method passes constant String of length 1 to character overridden method
+ Method {1} passes constant String of length 1 to character overridden method
+
+ This method passes a constant literal String of length 1 as a parameter to a method, that
+ exposes a similar method that takes a char. It is simpler and more expedient to handle one
+ character, rather than a String.
+
+
+ Instead of making calls like:
+
+ String myString = ...
+ if (myString.indexOf("e") != -1) {
+ int i = myString.lastIndexOf("e");
+ System.out.println(myString + ":" + i); //the Java compiler will use a StringBuilder internally here [builder.append(":")]
+ ...
+ return myString.replace("m","z");
+ }
+
+ Replace the single letter Strings with their char equivalents like so:
+
+
+ String myString = ...
+ if (myString.indexOf('e') != -1) {
+ int i = myString.lastIndexOf('e');
+ System.out.println(myString + ':' + i); //the Java compiler will use a StringBuilder internally here [builder.append(':')]
+ ...
+ return myString.replace('m','z');
+ }
+
+
+ ]]>
+
+
+
+
+ Method employs tail recursion
+ Method {1} employs tail recursion
+
+ This method recursively calls itself as the last statement of the method
+ (Tail Recursion). This method can be easily refactored into a simple loop, which
+ will make it more performant, and reduce the stack size requirements.
+ ]]>
+
+
+
+
+ Method returns different types of unrelated Objects
+ Method {1} returns different types of unrelated Objects
+
+ This method returns two or more unrelated types of objects (Related only through java.lang.Object).
+ This will be very confusing to the code that must call it.
+ ]]>
+
+
+
+
+ Method returns more specific type of object than declared
+ Method {1} returns more specific type of object than declared
+
+ This method is defined to return a java.lang.Object. However, the return types
+ returned from this method can be defined by a more specific class or interface. Since this
+ method is not derived from a superclass or interface, it would be more clear to
+ change the return type of this method.
+ ]]>
+
+
+
+
+ Inherited method returns more specific type of object than declared
+ Inherited method {1} returns more specific type of object than declared
+
+ This inherited method is defined to return a java.lang.Object. However, the return types returned
+ from this method can be defined by a more specific class or interface. If possible consider changing the
+ return type in the inheritance hierarchy of this method, otherwise the caller of this method will be brittle
+ in handling of the return type.
+ ]]>
+
+
+
+
+ Class doesn't serialize superclass fields
+ Class {0} doesn't serialize superclass fields
+
+ This method implements Serializable but is derived from a
+ class that does not. The super class has fields that are not serialized
+ because this class does not take the responsibility of writing these fields out
+ either using Serializable's writeObject method, or Externalizable's writeExternal
+ method. Therefore when this class is read from a stream, the superclass fields
+ will only be initialized to the values specified in its default constructor.
+ If possible, change the superclass to implement Serializable, or implement
+ Serializable or Externalizable methods in the child class.
+ ]]>
+
+
+
+
+ Comparator method doesn't seem to return all ordering values
+ Comparator method {1} doesn't seem to return all ordering values
+
+ This compareTo or compare method returns constant values for to represent less than,
+ equals and greater than. However it does not return each type. Given that comparators
+ are transitive, this seems incorrect.
+ ]]>
+
+
+
+
+ Method passes a negative number as a bit to a BitSet which isn't supported
+ Method {1} passes a negative number as a bit to a BitSet which isn't supported
+
+ This method passes a constant negative value as a bit position to a java.util.BitSet. The BitSet class
+ doesn't support negative values, and thus this method call will not work as expected.
+ ]]>
+
+
+
+
+ Method calls intern on a string constant
+ Method {1} calls intern on a string constant
+
+ This method calls intern on a constant string. As constant strings are already interned, this call
+ is superfluous.
+ ]]>
+
+
+
+
+ Method appears to pass character to StringBuffer or StringBuilder integer constructor
+ Method {1} appears to pass character to StringBuffer or StringBuilder integer constructor
+
+ This method constructs a StringBuffer or a StringBuilder using the constructor that takes an integer, but
+ appears to pass a character instead. It is probable that the author assumed that character would be appended to the
+ StringBuffer/Builder, but instead the integer value of the character is used as an initial size for the buffer.
+ ]]>
+
+
+
+
+ Method uses non standard math constant
+ Method {1} uses non standard math constant
+
+ This method defines its own version of PI or e and the value is not as precise as the
+ one defined in the constants Math.PI or Math.E. Use these constants instead.
+ ]]>
+
+
+
+
+ Method assigns a value to a local twice in a row
+ Method {1} assigns a value to a local twice in a row
+
+ This method assigns a value twice in a row in a stuttered way such as
+ a = a = 5; This is most probably a cut and paste error where the duplicate
+ assignment can be removed.
+ ]]>
+
+
+
+
+ Method incorrectly compares a floating point number to NaN
+ Method {1} compares a {3} to {4}.NaN
+
+ This method compares a double or float to the constant Double.NaN or Float.NaN.
+ You should use
+ Double.isNaN(d) or Float.isNaN(f)
+ if the variable is a primitive. If using a boxed primitive d.isNaN() or f.isNaN() should be used.
+ ]]>
+
+
+
+
+ Method passes double value to BigDecimal Constructor
+ Method {1} passes double value to BigDecimal Constructor
+
+ This method calls the BigDecimal constructor that takes a double, and passes a literal double constant value. Since
+ the use of BigDecimal is to get better precision than double, by passing a double, you only get the precision of double number
+ space. To take advantage of the BigDecimal space, pass the number as a string.
+ ]]>
+
+
+
+
+ Method passes an empty string to StringBuffer of StringBuilder constructor
+ Method {1} passes an empty string to StringBuffer of StringBuilder constructor
+
+ This method calls the StringBuffer or StringBuilder constructor passing in a constant empty string ("").
+ This is the same as calling the default constructor, but makes the code work harder. Consider passing in a
+ default size instead.
+ ]]>
+
+
+
+
+ Method calls equals on an enum instance
+ Method {1} calls equals on an enum instance
+
+ This method calls the equals(Object) method on an enum instance. Since enums values are singletons,
+ you can use == to safely compare two enum values. In fact, the implementation for Enum.equals does just
+ that.
+ ]]>
+
+
+
+
+ Method uses invalid C++ style null check on Boolean
+ Method {1} uses invalid C++ style null check on Boolean
+
+ This method attempts to check for null by just referring to the variable name
+ as would be done in C++. This ordinarily would be considered a compile error, except the
+ variable in question is a Boolean, which does an auto unbox to boolean.
+
+ if (b && b.booleanValue())
+
+ should be
+
+ if ((b != null) && b.booleanValue())
+
+
+ ]]>
+
+
+
+
+ Method fetches character array just to do the equivalent of the charAt method
+ Method {1} fetches character array just to do the equivalent of the charAt method
+
+ This method calls the toCharArray method on a String the fetch an array of characters, only
+ to retrieve one of those characters by index. It is more performant to just use the charAt method.
+ ]]>
+
+
+
+
+ Method uses a ternary operator to cast a boolean to true or false
+ Method {1} uses a ternary operator to cast a boolean to true or false
+
+ This method tests the value of a boolean and using a ternary operator to return either true or false.
+ The ternary operator is completely unnecessary, just use the original boolean value.
+ ]]>
+
+
+
+
+ Method possibly mixes up normal strings and empty strings in branching logic
+ Method {1} treats null and normal strings the same, when it should probably
+ treat null and empty strings the same
+
+ This method tests a string, and groups null values with real strings, leaving empty strings as another
+ case. That is, FindBugs has detected a structure like:
+
+ String a = null, b = "", c = "someString";
+ ...
+ String testStr = ...; //one of a, b or c
+ if (FLAWED_TEST_LOGIC) {
+ // Strings a and c fall into this branch... which is not typical.
+ } else {
+ // String b falls into this branch.
+ }
+
+
+ This might be perfectly valid, but normally, null strings and empty strings are logically handled the same way,
+ and so this test may be flawed.
+
Pattern found is one of the following:
+
+
if ((s == null) || (s.length() > 0)) --- did you mean
+ ((s == null) || (s.length() == 0))?
+
if ((s == null) || (s.length() != 0)) -- did you mean
+ ((s == null) || (s.length() == 0))?
+
if ((s != null) && (s.length() == 0)) -- did you mean
+ ((s != null) && (s.length() > 0)) or perhaps
+ ((s == null) || (s.length() == 0))?
+
+
+ ]]>
+
+
+
+
+ Method converts StringBuffer or Builder to String just to get its length
+ Method {1} converts StringBuffer or Builder to String just to get its length
+
+ This method calls the toString method on a StringBuffer or StringBuilder only to call length() on the resulting
+ string. It is faster, and less memory intensive to just call the length method directly on the StringBuffer or StringBuilder
+ itself.
+ ]]>
+
+
+
+
+ Method passes a non calendar object to Calendar.before or Calendar.after
+ Method {1} passes a non calendar object to Calendar.before or Calendar.after
+
+ This method passes a non calendar object to the java.util.Calendar.after or java.util.Calendar.before methods.
+ Even though these methods take an Object as a parameter type, only Calendar type objects are supported, otherwise
+ false is returned.
+ ]]>
+
+
+
+
+ Method calls keySet() just to call contains, use containsKey instead
+ Method {1} calls keySet() just to call contains, use containsKey instead
+
+ This method calls mySet.keySet().contains("foo") when mySet.containsKey("foo") is simpler.
+ ]]>
+
+
+
+
+ Method checks the size of a collection against zero rather than using isEmpty()
+ Method {1} checks the size of a collection against zero rather than using isEmpty()
+
+ This method calls the size() method on a collection and compares the result to zero to see if the collection
+ is empty. For better code clarity, it is better to just use col.isEmpty() or !col.isEmpty().
+ ]]>
+
+
+
+
+ Method calls getProperties just to get one property, use getProperty instead
+ Method {1} calls getProperties just to get one property, use getProperty instead
+
+
+
+
+ ]]>
+
+
+
+
+ Class defines a serialVersionUID as non private
+ Class {0} defines a serialVersionUID as non private
+
+ This class defines a static field 'serialVersionUID' to define the serialization
+ version for this class. This field is marked as non private. As the serialVersionUID only
+ controls the current class, and doesn't effect any derived classes, defining it as non
+ private is confusing. It is suggested you change this variable to be private.
+ ]]>
+
+
+
+
+ Method compares string without case after enforcing a case
+ Method {1} compares string without case after enforcing a case
+
+ This method compares two strings with compareToIgnoreCase or equalsIgnoreCase, after having
+ called toUpperCase or toLowerCase on the string in question. As you are comparing without
+ concern to case, the toUpperCase or toLowerCase calls are pointless and can be removed.
+ ]]>
+
+
+
+
+ Method passes a non array object to a parameter that expects an array
+ Method {1} passes a non array object to a parameter that expects an array
+
+ This method expects an array to be passed as one of its parameters, but unfortunately defines
+ the parameter as Object. This invocation of this method does not pass an array and will throw
+ an exception when run.
+ ]]>
+
+
+
+
+ Method passes an empty string to equalsIgnoreCase or compareToIgnoreCase
+ Method {1} passes an empty string to equalsIgnoreCase or compareToIgnoreCase
+
+ This method passes the empty string "" to equalsIgnoreCase or compareToIgnoreCase, as the empty string
+ is not case-sensitive using equals is simpler. It would be even simpler to do a length() == 0 test.
+ ]]>
+
+
+
+
+ Method trims a String temporarily
+ Method {1} trims a String temporarily
+
+ This method calls trim() on a String without assigning the new string to another variable.
+ It then calls length() or equals() on this trimmed string. If trimming the string was important
+ for determining its length or its equality, it should be trimmed when you actually go to use it.
+ It would make more sense to first trim the String, store the trimmed value in a variable, and then
+ continue to test and use that trimmed string.
+ ]]>
+
+
+
+
+ Method needlessly assigns a StringBuilder to itself, as it's mutable
+ Method {1} needlessly assigns a StringBuilder to itself, as it's mutable
+
+ This method calls StringBuilder.append and assigns the results to the same StringBuilder like:
+ sb = sb.append("foo")
+
StringBuilder is mutable this is not necessary.
+ This is also true of StringBuffer.
+ ]]>
+
+
+
+
+ Method uses iterator().next() on a List to get the first item
+ Method {1} uses iterator().next() on a List to get the first item
+
+ This Method calls myList.iterator().next() on a List to get the first item. It is more performant
+ to just use myList.get(0).
+ ]]>
+
+
+
+
+ Method appends two literal strings back to back to a StringBuilder
+ Method {1} appends two literal strings back to back to a StringBuilder
+
+ This method appends two literal strings to a StringBuilder back to back.
+ Modern compilers will optimize something like:
+
+ public static final string CONST_VAL = "there";
+ ...
+ String str = "Hello" + " "+ CONST_VAL + " " +"world!";
+
+ to:
+
+ public static final string CONST_VAL = "there";
+ ...
+ String str = "Hello there world!";
+
+ This means the concatenation is done during compile time, not at runtime, so there's no need to do:
+
+ public static final string CONST_VAL = "there";
+ ...
+ StringBuilder sb = new StringBuilder("Hello").append(" ").append(CONST_VAL).append(" ").append("world!");
+ String str = sb.toString();
+
+ which is harder to read and will result in more complex bytecode.
+
+
+
+ Simply append your constants with the "+" symbol, don't append them with StringBuilder.append().
+
+ ]]>
+
+
+
+
+ Method checks a reference for null before calling instanceof
+ Method {1} checks a reference for null before calling instanceof
+
+ This method checks a reference for null just before seeing if the reference is an instanceof some class.
+ Since instanceof will return false for null references, the null check is not needed.
+ ]]>
+
+
+
+
+ Method calls toString() on an instance of a class that hasn't overridden toString()
+ Method {1} calls toString() on an instance of a class that hasn't overridden toString()
+
+ This method calls toString() on an object that hasn't overridden the toString() method, and thus relies on
+ the version found in java.lang.Object. This string is just a raw display of the object's class and location, and
+ provides no information about the information of use. You should implement toString in this class.
+ ]]>
+
+
+
+
+ Method calls toString() on a String
+ Method {1} calls toString() on a String
+
+ This method calls toString on a String. Just use the object itself if you want a String.
+ ]]>
+
+
+
+
+ Method converts a String literal
+ Method {1} calls {3} on a String Literal
+
+ This method calls a converting method like toLowerCase() or trim
+ on a String literal. You should make the transformation yourself and use the transformed literal.
+
+
+ For example, instead of :
+
+ return "ThisIsAConstantString ".toLowerCase().trim();
+
+ just do
+
+ return "thisisaconstantstring";
+
+ for shorter and easier to read code. An exception might be made when locale-specific transformations need to be done (in the case of toUpperCase() and toLowerCase().
+
+ ]]>
+
+
+
+
+ Method calls equals(Object o) on a StringBuilder or StringBuffer
+ Method {1} calls equals(Object o) on a StringBuilder or StringBuffer
+
+ This method calls equals on a StringBuilder or StringBuffer. Surprisingly, these classes do not override
+ the equals method from Object, and so equals is just defined to be == (or same references). This is most
+ likely not what you would like. If you wish to check that the strings have the same characters, you need to
+ call toString() on these object and compare them as Strings.
+ ]]>
+
+
+
+
+ Method calls String.format on a static (non parameterized) format string
+ Method {1} calls String.format on a static (non parameterized) format string
+
+ This method calls String.format passing a static string as the format string that has no replacement markers
+ (starting with %). Thus no replacement will happen, and the format method is superfluous. If parameters were intended,
+ add the appropriate format markers as needed, otherwise, just remove the call to String.format and use the static
+ string as is.
+ ]]>
+
+
+
+
+ Method assigns a variable in a larger scope then is needed
+ Method {1} assigns a variable in a larger scope then is needed
+
+ THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD
+
This method assigns a value to a variable in an outer scope compared to where the variable is actually used.
+ Assuming this evaluation does not have side effects, the assignment can be moved into the inner scope (if block)
+ so that its execution time isn't taken up if the if guard is false. Care should be
+ taken however that the right hand side of the assignment does not contain side
+ effects that are required to happen, or that changes are not made further down that
+ will effect the execution of the assignment when done later on.
+ ]]>
+
+
+
+
+ Class implements interface by relying on unknowing superclass methods
+ Class {0} implements interface by relying on unknowing superclass methods
+
+ This class declares that it implements an interface, but does so by relying on methods supplied
+ by superclasses, even though those superclasses know nothing about the interface in question. If you wish
+ to have the child not implement all the methods of the interface, it would probably be better to declare
+ the superclass as implementing the interface, and if that class does not provide all the methods, then declare
+ that superclass abstract.
+ ]]>
+
+
+
+
+ Method deletes collection element while iterating
+ Method {1} deletes collection element while iterating
+
+ This method removes items from a collection using the remove method of the collection, while
+ at the same time iterating across the collection. Doing this will invalidate the iterator, and further
+ use of it, will cause ConcurrentModificationExceptions to be thrown. To avoid this, the remove
+ method of the iterator should be used.
+ ]]>
+
+
+
+
+ Method modifies collection element while iterating
+ Method {1} modifies collection element while iterating
+
+ This method modifies the contents of a collection using the collection API methods, while
+ at the same time iterating across the collection. Doing this will invalidate the iterator, and further
+ use of it, will cause ConcurrentModificationExceptions to be thrown.
+ ]]>
+
+
+
+
+ Method builds String array using String Tokenizing
+ Method {1} builds String array using String Tokenizing
+
+ This method uses a StringTokenizer to split up a String and then walks through the
+ separated elements and builds an array from these enumerated values. It is simpler
+ and easier to use the String.split method.
+
PLEASE NOTE: String.split will return an array of 1 element when passed the
+ empty string, as opposed to using StringTokenizer which returns false on the first
+ hasMoreElements/hasMoreTokens call. So you may need to use:
+
+ if (s.length() > 0)
+ return s.split(";");
+ return new String[0];
+
+ ]]>
+
+
+
+
+ Method uses rt.jar class or method that does not exist
+ Method {1} uses rt.jar class or method that does not exist for the version the class is compiled for
+
+ This method calls a method that does not exist, on a class that does not exist in the JDK that
+ this class has been compiled for. This can happen if you compile the class specifying the -source and
+ -target options, and use a version that is before the version of the compiler's JDK.
+ ]]>
+
+
+
+
+ Method uses simple loop to copy contents of one collection to another
+ Method {1} uses simple loop to copy contents of one collection to another
+
+ This method uses a simple for loop to copy the contents of a set, list, map key/value, array or other collection
+ to another collection. It is simpler and more straight forward to just call the addAll method of the destination collection
+ passing in the source collection. In the case that the source is an array, you can use Array.asList method to massage the array
+ into a collection.
+ ]]>
+
+
+
+
+ Private method only returns one constant value
+ Private method {1} only returns one constant value
+
+ This private or static method only returns one constant value. As this method is private or static,
+ its behavior can't be overridden, and thus the return of a constant value seems dubious.
+ Either the method should be changed to return no value, or perhaps another return value
+ was expected to be returned in another code path in this method.
+ ]]>
+
+
+
+
+ Method needlessly implements what is default streaming behavior
+ Method {1} needlessly implements what is default streaming behavior
+
+ This method implements the Serializable interface by performing the same operations that
+ would be done if this method did not exist. Since this is the case, this method is not needed.
+ ]]>
+
+
+
+
+ Class 'overloads' a method with both instance and static versions
+ Class {0} 'overloads' a method with both instance and static versions
+
+ This class 'overloads' the same method with both an instance and static version. As the use
+ of these two models is different, it will be confusing to the users of these methods.
+ ]]>
+
+
+
+
+ Unconstrained method converts checked exception to unchecked
+ Unconstrained method {1} converts checked exception to unchecked
+
+ This method is not constrained by an interface or superclass, but converts a caught checked exception
+ to unchecked exception and thrown. It would be more appropriate just throw the checked exception, adding
+ the exception to the throws clause of the method.
+ ]]>
+
+
+
+
+ Constrained method converts checked exception to unchecked instead of another allowable checked exception
+ Constrained method {1} converts checked exception to unchecked instead of another allowable checked exception
+
+ This method's exception signature is constrained by an interface of super class to not throw a
+ checked exception that was caught. Therefore this exception was converted to an unchecked exception and
+ thrown. It would probably be better to throw the closest checked exception allowed, and to annotate
+ the new exception with the original exception using the initial cause field.
+ ]]>
+
+
+
+
+ Constrained method converts checked exception to unchecked
+ Constrained method {1} converts checked exception to unchecked
+
+ This method's exception signature is constrained by an interface or super class to not throw
+ any checked exceptions. Therefore a caught checked exception was converted to an unchecked exception
+ and thrown. However it appears that the class in question is owned by the same author as the constraining
+ interface or superclass. Consider changes the signature of this method to include the checked exception.
+ ]]>
+
+
+
+
+ method converts an exception into a boolean 'error code' value
+ method {1} converts an exception into a boolean 'error code' value
+
+ This method catches and exception and returns a boolean that represents whether an exception occurred or not.
+ This throws away the value of exception handling and lets code ignore the resultant 'error code' return value.
+ You should just throw the exception to the caller instead.
+ ]]>
+
+
+
+
+ Method returns modified parameter
+ Method {1} returns modified parameter
+
+ This method appears to modify a parameter, and then return this parameter as the
+ methods return value. This will be confusing to callers of this method, as it won't be
+ apparent that the 'original' passed in parameter will be changed as well. If the purpose
+ of this method is to change the parameter, it would be more clear to change the method to
+ a have a void return value. If a return type is required due to interface or superclass contract,
+ perhaps a clone of the parameter should be made.
+ ]]>
+
+
+
+
+ Method passes constant to second (actual) assertion parameter
+ Method {1} passes constant to second (actual) assertion parameter
+
+ This method calls assert passing a constant value as the second of the two values. The assert
+ method assumes that the expected value is the first parameter, and so it appears that the order
+ of values has been swapped here.
+ ]]>
+
+
+
+
+ Method asserts that two doubles are exactly equal
+ Method {1} asserts that two doubles are exactly equal
+
+ This method calls assert with two doubles or Doubles. Due to the imprecision of doubles, you
+ should be using the assert method that takes a range parameter that gives a range of error.
+ ]]>
+
+
+
+
+ Method asserts that a value is true or false
+ Method {1} asserts that a value is true or false
+
+ This method asserts that a value is equal to true or false. It is simpler to just
+ use assertTrue, or assertFalse, instead.
+ ]]>
+
+
+
+
+ Method asserts that an auto-boxed value is not null
+ Method {1} asserts that an auto-boxed value is not null
+
+ This method asserts that a primitive value that was autoboxed into a boxed primitive was not
+ null. This will never happen, as primitives are never null, and thus the autoboxed value isn't
+ either.
+ ]]>
+
+
+
+
+ Method uses Java asserts rather than a junit assertion
+ Method {1} uses Java asserts rather than a junit assertion
+
+ This method uses a Java assert to assure that a certain state is in effect. As this is
+ a junit test it makes more sense to either check this condition with a junit assert, or allow
+ a following exception to occur.
+ ]]>
+
+
+
+
+ Method passes boolean expression to Assert.assertTrue
+ Method {1} passes boolean expression to Assert.assertTrue
+
+ This method evaluates a boolean expression and passes that to Assert.assertTrue. It is better
+ to pass the two values that are being equated to the Assert.assertEquals method so that the
+ junit failure method is more meaningful of the intended test.
+ ]]>
+
+
+
+
+ Method appears to have no assertions
+ Method {1} appears to have no assertions
+
+ This JUnit test method has no assertions. While a unit test could still be valid if it relies on whether
+ or not an exception is thrown, it is usually a sign of a weak test if there are no assertions. It is also
+ possible that assertions occur in a called method that is not seen by this detector, but this makes the logic of
+ this test more difficult to reason about.
+ ]]>
+
+
+
+
+ Clone method stores a new value to member field of source object
+ Clone method {1} stores a new value to member field of source object
+
+ The clone method stores a value to a member field of the source object. Normally, all
+ changes are made to the cloned object, and given that cloning is almost always considered
+ a read-only operation, this seems incorrect.
+ ]]>
+
+
+
+
+ Method throws exception with static message string
+ Method {1} throws exception with static message string
+
+ This method creates and throws an exception using a static string as the exceptions message.
+ Without any specific context of this particular exception invocation, such as the value of parameters,
+ key member variables, or local variables, it may be difficult to infer how this exception occurred. Consider
+ adding context to the exception message.
+ ]]>
+
+
+
+
+ Method modifies http session attribute without calling setAttribute
+ Method {1} modifies http session attribute without calling setAttribute
+
+ This method fetches a complex object from an HttpSession object, modifies this object, but does
+ not call setAttribute, to inform the application server that this attribute has been changed. This will
+ cause this attribute not to be updated in other servers in a clustered environment, as only changes marked
+ by a call to setAttribute are replicated.
+ ]]>
+
+
+
+
+ Method incorrectly passes exception as first argument to logger method
+ Method {1} incorrectly passes exception as first argument to logger method
+
+ This method passes an exception as the first argument to a logger method. The stack
+ trace is potentially lost due to the logger emitting the exception using toString(). It
+ is better to construct a log message with sufficient context and pass the exception as
+ the second argument to capture the stack trace.
+ ]]>
+
+
+
+
+ Method specifies an unrelated class when allocating a Logger
+ Method {1} specifies an unrelated class when allocating a Logger. Saw "{3}", expected "{4}".
+
+ This method creates a Logger by passing in a specification for a class that is unrelated
+ to the class in which the logger is going to be used. This is likely caused by copy/paste code.
+ ]]>
+
+
+
+
+ Constructor declares a Logger parameter
+ Constructor {1} declares a Logger parameter
+
+ This constructor declares a parameter that is a Logger. As loggers are meant to be
+ created statically per class, it doesn't make sense that you would pass a Logger from one
+ class to another. Declare the Logger static in each class instead.
+ ]]>
+
+
+
+
+ Method stutters exception message in logger
+ Method {1} stutters exception message in logger
+
+ This method uses a logger method that takes an exception, and passes the result of
+ the getMessage() method on the exception that occurred as the log message.
+ Since you are already passing in the exception, that message is already present in the
+ logs, and by passing it in as the message, you are just stuttering information.
+ It would be more helpful to provide a hand written message that describes the error in
+ this method, possibly including the values of key variables.
+ ]]>
+
+
+
+
+ Method attempts to log using numbered formatting anchors
+ Method {1} attempts to log using numbered formatting anchors
+
+ This method attempts to use an SLF4J logger to log a parameterized expression using formatting anchors.
+ However, SLF4J uses simple non numbered anchors such as {}, rather than anchors with digits in them as the
+ code uses. Thus no parameter replacement will occur.
+ ]]>
+
+
+
+
+ Method passes an incorrect number of parameters to an SLF4J logging statement
+ Method {1} passes an incorrect number of parameters to an SLF4J logging statement
+
+ This method passes the wrong number of parameters to a SLF4J logging method (error, warn, info, debug) based on the number of anchors {} in the
+ format string. An additional exception argument is allowed if found.
+ ]]>
+
+
+
+
+ Method creates exception with logger parameter markers in message
+ Method {1} creates exception with logger parameter markers in message
+
+ This method creates a standard exception passing a message string which contains an SLF4J style
+ parameter marker '{}'. This marker will not be translated as it is not processed by the Exception class.
+
+ ]]>
+
+
+
+
+ Method passes a concatenated string to SLF4J's format string
+ Method {1} passes a concatenated string to SLF4J's format string
+
+ This method uses an SLF4J logger to log a string, where the first (format) string is created using concatenation.
+ You should use {} markers to inject dynamic content into the string, so that String building is delayed until the
+ actual log string is needed. If the log level is high enough that this log statement isn't used, then the appends
+ will never be executed.
+ ]]>
+
+ '
+
+
+ Class relies on internal API classes
+ Class {0} relies on internal API classes
+
+ This class makes use of internal API classes. As these
+ classes are not documented, nor externally released as part of the API, they are subject
+ to change or removal. You should not be using these classes.
+ Packages that shouldn't be used are:
+
+
com.sun.xxx
+
org.apache.xerces.xxx
+
org.apache.xalan.xxx
+
+ ]]>
+
+
+
+
+ Method uses a set of collections
+ Method {1} uses a set of collections
+
+ This method creates a set that contains other collections, or a Map whose keySet is
+ another collection. As collections tend to calculate hashCode, equals and compareTo by
+ iterating the contents of the collection, this can perform poorly.
+
In addition, when a set is used, you typically are using it to do 'contains', or 'find'
+ type functionality, which seems dubious when done on a collection
+
Finally, as a collection is often modified, problems will occur if the collection is
+ contained in a set, because the hashCode, equals or compareTo values will change while the
+ collection is in the set
+
If you wish to maintain a collection of collections, it is probably better to use a List
+ as the outer collection
+ ]]>
+
+
+
+
+ Non derivable method declares throwing an exception that isn't thrown
+ Non derivable method {1} declares throwing an exception that isn't thrown
+
+ This method declares that it throws a checked exception that it does not throw. As this method is
+ either a constructor, static method or private method, there is no reason for this method to declare
+ the exception in its throws clause, and just causes calling methods to unnecessarily handle an exception
+ that will never be thrown. The exception in question should be removed from the throws clause.
+ ]]>
+
+
+
+
+ Method declares throwing two or more exceptions related by inheritance
+ Method {1} declares throwing two or more exceptions related by inheritance
+
+ This method declares that it throws an exception that is the child of another exception that is also declared to be thrown.
+ Given that the parent exception is declared, there is no need for the child exception to also be declared, and just adds confusion.
+ ]]>
+
+
+
+
+ Method checks the result of a new allocation
+ Method {1} checks the result of a new allocation
+
+ This method allocations an object with new, and then checks that the object is null
+ or non null. As the new operator is guaranteed to either succeed or throw an exception,
+ this null check is unnecessary and can be removed.
+ ]]>
+
+
+
+
+ Class appears to implement the old style type safe enum pattern
+ Class {0} appears to implement the old style type safe enum pattern
+
+ This class appears to implement the old style type safe enum pattern that was used in place of
+ real enums. Since this class is compiled with Java 1.5 or better, it would be simpler and more
+ easy to understand if it was just switched over to an enum.
+ ]]>
+
+
+
+
+ Code calls a method passing the same value to two different arguments
+ Code {1} calls a method passing the same value to two different arguments
+
+ This method calls a method passing the same value for two or more of the parameters.
+ Often this is a cut/paste bug, but if not, it is confusing why you would pass the same value for two
+ different parameters. Perhaps an alternative method that just takes one parameter should be overridden
+ in this case.
+ ]]>
+
+
+
+
+ Method returns null for Boolean type
+ Method {1} returns null for Boolean type
+
+ This method declares that it returns a Boolean value. However the code
+ can return a null value. As this is now three values that can be returned;
+ Boolean.TRUE, Boolean.FALSE, null; you have changed what a Boolean means.
+ It would be clearer to just create a new Enum that has the three values
+ you want, and define that the method returns that type.
+ ]]>
+
+
+
+
+ Method returns an array that appears not to be initialized
+ Method {1} returns an array that appears not to be initialized
+
+ This method returns an array that was allocated but apparently not initialized. It is
+ possible that the caller of this method will do the work of initializing this array, but
+ that is not a common pattern, and it is assumed that this array has just been forgotten to
+ be initialized.
+ ]]>
+
+
+
+
+ Method performs algorithmic operations on the result of a toString() call
+ Method {1} performs algorithmic operations on the result of a toString() call
+
+ This method calls algorithmic operations on a String that was returned from a toString() method.
+ As these methods are for debugging/logging purposes, it shouldn't be the basis of core logic in your code.
+ ]]>
+
+
+
+
+ Method uses the same HttpSession attribute name but with different casing
+ Method {1} uses the same HttpSession attribute name but with different casing
+
+ This method sets or gets an HttpSession attribute with a parameter name that was used in other locations
+ but with a different casing. As HttpSession attribute are case-sensitive, this will be very confusing.
+ ]]>
+
+
+
+
+ Method uses the same HttpRequest parameter name but with different casing
+ Method {1} uses the same HttpRequest parameter name but with different casing
+
+ This method fetches an HttpServletRequest parameter with a parameter name that was used in other locations
+ but with a different casing. As HttpServletRequest parameters are case-sensitive, this will be very confusing.
+ ]]>
+
+
+
+
+ Method manually casts the right hand side of an assignment more specifically than needed
+ Method {1} manually casts the right hand side of an assignment more specifically than needed
+
+ This method casts the right hand side of an expression to a class that is more specific than the
+ variable on the left hand side of the assignment. The cast only has to be as specific as what the variable
+ that is on the left. Using a more specific type on the right hand side just increases cohesion.
+ ]]>
+
+
+
+
+ Method defines parameters more abstractly than needed to function properly
+ Method {1} defines parameters more abstractly than needed to function properly
+
+ This method defines parameters at a more abstract level than is actually needed to function correctly,
+ as the code casts these parameters to more concrete types. Since this method is not derivable, you should
+ just define the parameters with the type that is needed.
+ ]]>
+
+
+
+
+ Equals method compares this object against other types in a non symmetric way
+ Equals method {1} compares this object against other types in a non symmetric way
+
+ This class implements an equals method that compares this object against another type of object.
+ This is almost always a bad thing to do, but if it is to be done, you must make sure that the basic
+ symmetry rule of equivalence is maintained, that being if a equals b, then b equals a. It does not
+ appear that the class that is being compared to this class knows about this class, and doesn't compare itself
+ to this.
+ ]]>
+
+
+
+
+ Method performs a contravariant array assignment
+ Method {1} performs a contravariant array assignment
+
+ This method contains a contravariant array assignment. Since arrays are mutable data structures, their use
+ must be restricted to covariant or invariant usage.
+
+
+ class A {}
+ class B extends A {}
+
+ B[] b = new B[2];
+ A[] a = b;
+
+ ]]>
+
+
+
+
+ Method performs a contravariant array element assignment
+ Method {1} performs a contravariant array element assignment
+
+ This method contains a contravariant array element assignment. Since arrays are mutable
+ data structures, their use must be restricted to covariant or invariant usage.
+
+
+ class A {}
+ class B extends A {}
+
+ B[] b = new B[2];
+ A[] a = b;
+ a[0] = new A(); // results in ArrayStoreException (Runtime)
+
+ ]]>
+
+
+
+
+ Serializable class defines a final transient field
+ Serializable class {0} defines a final transient field
+
+ This serializable class defines a field as both transient and final. As transient fields
+ are not serialized across the stream, it is required that some piece of code reinitialize that field
+ when it is deserialized. But since constructors aren't called when deserialization, the field is not initialized.
+ And since the field is final, no other method can initialize it as well.
+ ]]>
+
+
+
+
+ Method tests a field for not null as guard and reassigns it
+ Method {1} tests a field for not null as guard and reassigns it
+
+ This method tests a field to make sure it's not null before executing a conditional block of
+ code. However in the conditional block it reassigns the field. It is likely that the guard
+ should have been a check to see if the field is null, not that the field was not null.
+ ]]>
+
+
+
+
+ Method tests a local variable for not null as guard and reassigns it
+ Method {1} tests a local variable for not null as guard and reassigns it
+
+ This method tests a local variable to make sure it's not null before executing a conditional block of
+ code. However in the conditional block it reassigns the local variable. It is likely that the guard
+ should have been a check to see if the local variable is null, not that the local variable was not null.
+ ]]>
+
+
+
+
+ Method calls Runtime.exit() or Runtime.halt()
+ Method {1} calls {2}
+
+ Calling Runtime.exit() or Runtime.halt() shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.
+ ]]>
+
+
+
+
+ Method triggers finalization
+ Method {1} triggers finalization when calling {2}
+
+ Manually triggering finalization can result in serious performance problems and may be masking resource cleanup bugs.
+ ]]>
+
+
+
+
+ Method calls BigDecimal.equals()
+ Method {1} calls BigDecimal.equals(), which is normally a mistake
+
+ equals() being called to compare two java.math.BigDecimal numbers. This is normally a mistake, as two BigDecimal objects are only equal if they are equal in both value and scale, so that 2.0 is not equal to 2.00. To compare BigDecimal objects for mathematical equality, use compareTo() instead.
+ ]]>
+
+
+
+
+ Method calls InetAddress.getLocalHost()
+ Method {1} calls InetAddress.getLocalHost(), which may be a security risk
+
+ Do not call InetAddress.getLocalHost() on multihomed servers. On a multihomed server, InetAddress.getLocalHost() simply returns the IP address associated with the server's internal hostname. This could be any of the network interfaces, which could expose the machine to security risks. Server applications that need to listen on sockets should add configurable properties to define which network interfaces the server should bind.
+ ]]>
+
+
+
+
+ Method creates promiscuous ServerSocket object
+ Method {1} creates a promiscuous ServerSocket, which may be a security risk
+
+ Do not use the ServerSocket constructor or ServerSocketFactory.createServerSocket() factory methods that accepts connections on any network interface. By default, an application that listens on a socket will listen for connection attempts on any network interface, which can be a security risk. Only the long form the ServerSocket constructor or ServerSocketFactory.createServerSocket() factory methods take a specific local address to define which network interface the socket should bind.
+ ]]>
+
+
+
+
+ Method creates insecure Random object
+ Method {1} creates an insecure Random object, which may be a security risk
+
+ Random() constructor without a seed is insecure because it defaults to easily guessable seed: System.currentTimeMillis(). Initialize seed like new Random(SecureRandom.getInstance("SHA1PRNG").nextLong()) or replace Random() with SecureRandom.getInstance("SHA1PRNG") instead.
+ "SHA1PRNG" is the random algorithm supported on all platforms.
+
+
+
+ As of Java 6, you may use new Random(new SecureRandom().nextLong()) or new SecureRandom() instead.
+
+ ]]>
+
+
+
+
+ Method calls deprecated SecureRandom method
+ Method {1} calls deprecated SecureRandom method {2}
+
+ The In JDK 1.5 or less, SecureRandom() constructors and SecureRandom.getSeed() method are recommended against using. Call SecureRandom.getInstance() and SecureRandom.getInstance().generateSeed() instead.
+ ]]>
+
+
+
+
+ Method uses suspicious thread priorities
+ Method {1} uses suspicious thread priorities by calling method {2}
+
+ Getting or setting thread priorities is not portable and could cause or mask race conditions.
+ ]]>
+
+
+
+
+ Method attempts to manually schedule threads
+ Method {1} attempts to manually schedule threads by calling method {2}
+
+ Manual thread scheduling with Thread.sleep() or Thread.yield() has no guaranteed semantics and is often used to mask race conditions.
+ ]]>
+
+
+
+
+ Method sleeps without timeout
+ Method {1} sleeps without timeout when calling {2}
+
+ Calling one of the following methods without timeout could block forever. Consider using a timeout to detect deadlocks or performance problems. Methods: Thread.join(), Object.wait(), Condition.await(), Lock.lock(), Lock.lockInterruptibly(), ReentrantLock.lock(), ReentrantLock.lockInterruptibly()
+ ]]>
+
+
+
+
+ Method ignores Lock's fairness settings by calling tryLock()
+ Method {1} ignores Lock's fairness settings by calling {2}
+
+ Calling Lock.tryLock() or ReentrantLock.tryLock() without a timeout does not honor the lock's fairness setting. If you want to honor the fairness setting for this lock, then use tryLock(0, TimeUnit.SECONDS) which is almost equivalent (it also detects interruption).
+ ]]>
+
+
+
+
+ Method calls Condition.signal() rather than Condition.signalAll()
+ Method {1} calls Condition.signal() rather than Condition.signalAll()
+
+ Condition.signalAll() is preferred over Condition.signal(). Calling signal() only wakes up one thread, meaning that the thread woken up might not be the one waiting for the condition that the caller just satisfied.
+ ]]>
+
+
+
+
+ Method tests if a lock is locked
+ Method {1} tests if a lock is locked by calling {2}
+
+ Calling ReentrantLock.isLocked() or ReentrantLock.isHeldByCurrentThread() might indicate race conditions or incorrect locking. These methods are designed for use in debug code or monitoring of the system state, not for synchronization control.
+ ]]>
+
+
+
+
+ Method encodes String bytes without specifying the character encoding
+ Method {1} encodes String bytes without specifying the character encoding
+
+ The behavior of the String(byte[] bytes) and String.getBytes() is undefined if the string cannot be encoded in the platform's default charset. Instead, use the String(byte[] bytes, String encoding) or String.getBytes(String encoding) constructor which accepts the string's encoding as an argument. Be sure to specify the encoding used for the user's locale.
+
+
As per the Java specifications, "UTF-8", "US-ASCII", "UTF-16" and "ISO-8859-1" will all be valid encoding charsets. If you aren't sure, try "UTF-8".
+
+
New in Java 1.7, You can specify an encoding from StandardCharsets, like StandardCharsets.UTF_8. These are generally preferrable because you don't have to deal with UnsupportedEncodingException.
+ ]]>
+
+
+
+
+ Method calls Locale.setDefault()
+ Method {1} calls Locale.setDefault(), changing locale for all threads
+
+ Do not use the Locale.setDefault() method to change the default locale. It changes the JVM's default locale for all threads and makes your applications unsafe to threads. It does not affect the host locale. Since changing the JVM's default locale may affect many different areas of functionality, this method should only be used if the caller is prepared to reinitialize locale-sensitive code running within the same Java Virtual Machine, such as the user interface.
+ ]]>
+
+
+
+
+ Method uses reflection to call a method available on java.lang.Object
+ Method {1} uses reflection to call a method available on java.lang.Object
+
+ This method uses reflection to call a method that is defined in java.lang.Object.
+ As these methods are always available, it is not necessary to call these methods with
+ reflection.
+ ]]>
+
+
+
+
+ Method puts non-String values into a Properties object
+ Method {1} puts non-String values into a Properties object
+
+ This method places non-String objects into a Properties object. As the Properties object
+ is intended to be a String to String map, putting non String objects is wrong, and takes advantage
+ of a design flaw in the Properties class by deriving from Hashtable instead of using aggregation.
+ If you want a collection that holds other types of objects, use a Hashtable, or better still newer collections
+ like HashMap or TreeMap.
+ ]]>
+
+
+
+
+ Method uses Properties.put instead of Properties.setProperty
+ Method {1} uses Properties.put instead of Properties.setProperty
+
+ This method uses the inherited method from Hashtable put(String key, Object value) in
+ a Properties object. Since the Properties object was intended to be only a String to String
+ map, use of the derived put method is discouraged. Use the Properties.setProperty method instead.
+ ]]>
+
+
+
+
+ Method allocates an object that is used in a constant way in a loop
+ Method {1} allocates an object that is used in a constant way in a loop
+
+ This method allocates an object using the default constructor in a loop, and then
+ only uses it in a quasi-static way. It is never assigned to anything that lives outside
+ the loop, and could potentially be allocated once outside the loop. Often this can be
+ achieved by calling a clear() like method in the loop, to reset the state of the object
+ in the loop.
+ ]]>
+
+
+
+
+ Method creates and initializes a collection but never reads or gains information from it
+ Method {1} creates and initializes a collection but never reads or gains information from it
+
+ This method creates and initializes a collection but then never access this collection
+ to gain information, or fetch items from the collection. It is likely that this collection
+ is left over from a past effort, and can be removed.
+ ]]>
+
+
+
+
+ Class creates and initializes a collection but never reads or gains information from it
+ Class {0} creates and initializes a collection but never reads or gains information from it
+
+ This class creates and initializes a collection as a field but then never access this collection
+ to gain information, or fetch items from the collection. It is likely that this collection
+ is left over from a past effort, and can be removed.
+ ]]>
+
+
+
+
+ Method defines parameter list with array as last argument, rather than vararg
+ Method {1} defines parameter list with array as last argument, rather than vararg
+
+ This method defines a parameter list that ends with an array. As this class is compiled with
+ Java 1.5 or better, this parameter could be defined as a vararg parameter instead, which can be
+ more convenient for client developers to use. This is not a bug, per se, just an improvement.
+ ]]>
+
+
+
+
+ Method serializes an instance of a non-static inner class
+ Method {1} serializes an instance of a non-static inner class
+
+ This method serializes an instance of a non-static inner class. Since this class has a
+ reference to the containing class, this outer class will be serialized as well. This is often
+ not intentional, and will make the amount of data that is serialized much more than is needed.
+ If the outer classes is not desired to be serialized, either make the inner class static, or
+ pull it out into a separate "first class" class.
+ ]]>
+
+
+
+
+ Method uses a Side Effect Constructor
+ Method {1} uses a Side Effect Constructor
+
+ This method creates an object but does not assign this object to any variable or field.
+ This implies that the class operates through side effects in the constructor, which is a
+ bad pattern to use, as it adds unnecessary coupling. Consider pulling the side effect out of
+ the constructor, into a separate method, or into the calling method.
+ ]]>
+
+
+
+
+ Method uses same bean's getter value for setter
+ Method {1} uses same bean's getter value for setter
+
+ This method retrieves the property of a Java bean, only to use it in the setter
+ for the same property of the same bean. This is usually a copy/paste typo.
+ ]]>
+
+
+
+
+ Method allocations a java.awt.Graphics object without disposing it
+ Method {1} allocations a java.awt.Graphics object without disposing it
+
+ This method allocates a java.awt.Graphics object but doesn't dispose of it when done. While
+ the garbage collector will clean this up, given that a large number of Graphics objects can be
+ created in a short period of time, it is recommended that you explicitly dispose() of them.
+ ]]>
+
+
+
+
+ Method stacks similar try/catch blocks
+ Method {1} stacks similar try/catch blocks
+
+ This method declares two try catch blocks one after another, where each
+ catch block catches the same type of exception. They also throw uniformly the
+ same type of exception. These two catch blocks can be combined into one to
+ simplify the method.
+ ]]>
+
+
+
+
+ Method returns the result of invoking equals() on EqualsBuilder
+ Method {1} returns the result of invoking equals() in EqualsBuilder
+
+ This method returns the result of equals on the EqualsBuilder type
+ instead of calling the method isEqual().
+ ]]>
+
+
+
+
+ Method returns the result of invoking hashCode() on HashCodeBuilder
+ Method {1} returns the result of invoking hashCode() in HashCodeBuilder
+
+ This method returns the result of hashCode on the HashCodeBuilder type
+ instead of calling the method toHashCode().
+ ]]>
+
+
+
+
+ Method returns the result of invoking toString() without intermediate invocation of append() in ToStringBuilder
+ Method {1} returns the result of invoking toString() without intermediate invocation of append() in ToStringBuilder
+
+ This method returns the result of toString() on ToStringBuilder without an
+ intermediate invocation of append().
+ ]]>
+
+
+
+
+ Method compares class name instead of comparing class
+ Method {1} compares class name instead of comparing the class
+
+ In a JVM, Two classes are the same class (and consequently the same type) if
+ they are loaded by the same class loader, and they have the same fully
+ qualified name [JVMSpec 1999].
+
+ Comparing class name ignores the class loader.
+ ]]>
+
+
+
+
+ Method uses backport concurrency utils
+ Method {1} backport concurrency utils
+
+ This class uses Backport Utils concurrent classes. Updated/Efficient version of these
+ classes are available in versions of the JDK 5.0 and higher, and these
+ classes should only be used if you are targeting JDK 1.4 and lower.
+ ]]>
+
+
+
+
+ Clone method declares it returns an Object
+ Clone method {1} declares it returns an Object
+
+ This class implements the Cloneable interface but defines its clone method to return an
+ Object. Since most likely users of this method will need to cast it to the real type, this will
+ be more painful than necessary. Just declare the return value to be the type of this class.
+ ]]>
+
+
+
+
+ Clone method declares it returns a type different then the owning class
+ Clone method {1} declares it returns a type different then the owning class
+
+ This class implements the Cloneable interface but defines its clone method to return a type
+ that is different than the class itself, or any interfaces that the class implements.
+ ]]>
+
+
+
+
+ Clone method declares it throws CloneNotSupportedException
+ Clone method {1} declares it throws CloneNotSupportedException
+
+ This class implements the Cloneable interface but defines its clone method to still return
+ a CloneNotSupportedException. Since you are implementing clone() it would make sense that the method
+ in question will not throw that exception, so annotating your method with it just makes client use
+ of your more painful as they have to handle an exception that will never happen. Just remove the
+ throws clause from your method.
+ ]]>
+
+
+
+
+ Method calls Array.asList on an array of primitive values
+ Method {1} calls Array.asList on an array of primitive values
+
+ This method passes an array of primitive values to the Array.asList call. As primitive
+ values in arrays aren't automatically promoted to boxed primitives in arrays, the asList call
+ cannot convert this array in a list of boxed primitives. It therefore just creates an array
+ with one item in it, the array itself. This is rarely what is desired.
+ ]]>
+
+
+
+
+ Method does not presize the allocation of a collection
+ Method {1} does not presize the allocation of a collection
+
+ This method allocates a collection using the default constructor even though it is known
+ a priori how many items are going to be placed in the collection (or at least a reasonable guess)
+ and thus needlessly causes intermediate reallocations of the collection.
+
You can use the constructor that takes an initial size and that will be much better, but
+ due to the loadFactor of Maps and Sets, even this will not be a correct estimate.
+
If you are using guava, use its methods that allocate maps and sets with a predetermined size,
+ to get the best chance for no reallocations, such as:
+
+
Sets.newHashSetWithExpectedSize(int)
+
Maps.newHashMapWithExpectedSize(int)
+
+
+ ]]>
+
+
+
+
+ Method declares unbound method template parameter(s)
+ Method {1} declares unbound method template parameter(s)
+
+ This method declares a method level template parameter that is not bound by any parameter of this
+ method. Therefore the template parameter adds no validation or type safety and can be removed, as it's
+ just confusing to the reader.
+ ]]>
+
+
+
+
+ Method ignores return value of a non mutating method
+ Method {1} ignores return value of a non mutating method
+
+ This method ignores the return value of a common method that is assumed to be none mutating.
+ If this method does in fact not modify the object it is called on, there is no reason to call
+ this method, and it can be removed.
+ ]]>
+
+
+
+
+ Method attempts to access an array element outside the array's size
+ Method {1} attempts to access an array element outside the array's size
+
+ This method access an array element using a literal index that is know to be outside the size of the specified
+ array. This will cause an ArrayIndexOutOfBoundsException at runtime.
+ ]]>
+
+
+
+
+ Method attempts to store an array element to an array that does not appear to be allocated
+ Method {1} attempts to store an array element to an array that does not appear to be allocated
+
+ This method attempts to store an array element into an array that appears to not have been allocated.
+ ]]>
+
+
+
+
+ Method passes an invalid value as a method argument
+ Method {1} passes an invalid value as a method argument
+
+ This method passes an invalid constant value to a method parameter that expects only a select number of possible values.
+ This is likely going to cause this method to fail to operate correctly.
+ ]]>
+
+
+
+
+ Collection variable is named with a different type of collection in the name
+ Collection variable {1} is named with a different type of collection in the name
+
+ This class defines a field or local collection variable with a name that contains a different type
+ of collection in its name. An example would be a Set called userList. This is confusing to the reader,
+ and likely caused by a previous refactor of type, without changing the name.
+ ]]>
+
+
+
+
+ Simple field is used like an enum
+ Simple field {1} is used like an enum
+
+ This field, although defined as a simple variable (int, String, etc) only has a set of constant values
+ assigned to it. Thus it appears to be used like an enum value, and should probably be defined as such.
+
+ ]]>
+
+
+
+
+ Static or private method has unused parameters
+ Static or private method {1} has unused parameters
+
+ This method defines parameters that are never used. As this method is either static of private,
+ and can't be derived from, it is safe to remove these parameters and simplify your method.
+ You should consider, while unlikely, that this method may be used reflectively, and thus you will
+ want to change that call as well.
+ ]]>
+
+
+
+
+ Test for circular dependencies among classes
+ Class {0} has a circular dependency with other classes
+
+
+ This class has a circular dependency with other classes. This makes building these classes
+ difficult, as each is dependent on the other to build correctly. Consider using interfaces
+ to break the hard dependency.
+
+ ]]>
+
+
+
+
+ This method attempts to modify collection that appears to possibly be immutable
+ This method {1} attempts to modify collection that appears to possibly be immutable
+
+ This method attempts to modify a collection that it got from a source that could potentially have created an
+ immutable collection, thru Arrays.asList, Collections.unmodifiableXXX, or one of guava's methods. Doing so will cause
+ an exception, as these collections are not mutable.
+ ]]>
+
+
+
+
+ ExecutorService field doesn't ever get shutdown
+ ExecutorService {2} is instantiated, but never shutdown, potentially preventing the entire JVM from shutting down
+
+ Most ExecutorService objects must be explicitly shutdown,
+ otherwise, their internal threads can prolong the running of the JVM, even when everything
+ else has stopped.
+
+
FindBugs has detected that there are no calls to either the shutdown() or shutdownNow()
+ method, and thus, the ExecutorService is not guaranteed to ever terminate. This is especially
+ problematic for Executors.newFixedThreadPool() and most of the other convenience methods in
+ the Executors class.
+
+
Even though there are some exceptions to this, particularly when a custom ThreadFactory is
+ provided, or for ThreadPoolExecutors with allowsCoreThreadTimeOut() set to true,
+ it is good practice to explicitly shutdown the ExecutorService when its utility is done.
+ ]]>
+
+
+
+
+ Suspicious Local Executor Service
+ ExecutorService is created as a local variable, which is unusual
+
+ ExecutorServices are typically instantiated as fields so that many tasks can be executed on a controlled number of Threads across many method calls. Therefore, it is unusual for ExecutorServices to be a local variable, where tasks will be added only one time, in the enclosing method.
+
+
Furthermore, when a local ExecutorService reaches the end of scope and goes up for garbage collection, the internal Threads are not necessarily terminated and can prevent the JVM from ever shutting down.
+
+
Consider making this local variable a field and create a method that will explicitly shutdown the ExecutorService
+ ]]>
+
+
+
+
+ An ExecutorService isn't shutdown before the reference to it is lost
+ ExecutorService {2} is replaced with another ExecutorService without being shutdown, potentially preventing the entire JVM from shutting down
+
+ Most ExecutorService objects must be explicitly shutdown, otherwise, their internal threads can prevent the JVM from ever shutting down, even when everything else has stopped.
+
+
FindBugs has detected that something like the following is happening:
+
+ ExecutorService executor = ... //e.g. Executors.newCachedThreadPool();
+ ...
+ public void reset() {
+ this.executor = Executors.newCachedThreadPool();
+ this.executor.execute(new SampleExecutable());
+ }
+
+ For normal objects, losing the last reference to them like this would trigger the object to be cleaned up
+ in garbage collection. For ExecutorServices, this isn't enough to terminate the internal threads in the
+ thread pool, and the ExecutorService isn't guaranteed to shutdown, causing the JVM to never stop.
+ To fix this, simply add a call to shutdown() like this:
+
+ ExecutorService executor = ... //e.g. Executors.newCachedThreadPool();
+ ...
+ public void reset() {
+ this.executor.shutDown();
+ this.executor = Executors.newCachedThreadPool();
+ this.executor.execute(new SampleExecutable());
+ }
+
+
+
+
Even though there are some exceptions to this, particularly when a custom ThreadFactory is
+ provided, or for ThreadPoolExecutors with allowsCoreThreadTimeOut() set to true,
+ it is good practice to explicitly shutdown the ExecutorService at the end of execution, or
+ when it is being replaced.
+
+
Note:ExecutorServices are generally created once in a program's life cycle. If you find yourself
+ replacing the ExecutorService, perhaps you may consider restructuring your code to use calls like
+ awaitTermination() or Futures/Callables to avoid recreating the ExecutorService.
+ ]]>
+
+
+
+
+ Unreleased HttpRequest network resources (field)
+ The HttpRequest field {1} does not release its network resources, which could freeze the running code
+
+ FindBugs has detected an org.apache.http.HttpRequest (e.g. HttpGet, HttpPost, etc)
+ that didn't release its associated resources. Code like the following:
+
+ private HttpGet httpGet;
+ ...
+ public String requestInfo(URI u) {
+ this.httpGet = new HttpGet(u);
+ try(CloseableHttpResponse response = client.execute(httpGet);) {
+ return getResponseAsString(response);
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ will freeze after a few requests, usually with no indication as to why.
+
+
+ The reason this code freezes is because org.apache.http.HttpRequests need explicitly release their connection
+ with a call to either reset() or releaseConnection(). The above example can be easily fixed:
+
+ private HttpGet httpGet;
+ ...
+ public String requestInfo(URI u) {
+ this.httpGet = new HttpGet(u);
+ try(CloseableHttpResponse response = client.execute(httpGet);) {
+ return getResponseAsString(response);
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ finally {
+ this.httpGet.reset();
+ }
+ return null;
+ }
+
+
+ ]]>
+
+
+
+
+ Unreleased HttpRequest network resources (local)
+ The local HttpRequest {1} does not release its network resources before being garbage collected, which could freeze the running code
+
+ FindBugs has detected an org.apache.http.HttpRequest (e.g. HttpGet, HttpPost, etc)
+ that didn't release its associated resources. Code like the following:
+
+ public String requestInfo(URI u) {
+ HttpGet httpGet = new HttpGet(u);
+ try(CloseableHttpResponse response = client.execute(httpGet);) {
+ return getResponseAsString(response);
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ will freeze after a few requests, usually with no indication as to why.
+
+
+ The reason this code freezes is because org.apache.http.HttpRequests need explicitly release their connection
+ with a call to either reset() or releaseConnection(), even if the request is a local.
+ The garbage collector will not release these resources, leading to the frustrating freezing scenario described above.
+
+ The above example can be easily fixed:
+
+ public String requestInfo(URI u) {
+ HttpGet httpGet = new HttpGet(u);
+ try(CloseableHttpResponse response = client.execute(httpGet);) {
+ return getResponseAsString(response);
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ finally {
+ httpGet.reset();
+ }
+ return null;
+ }
+
+
+ ]]>
+
+
+
+
+ This method is too long to be compiled by the JIT
+ This method {1} is too long to be compiled by the JIT
+
+ This method is longer than 8000 bytes. By default the JIT will not attempt to compile this method no matter
+ how hot it is, and so this method will always be interpreted. If performance is important, you should consider
+ breaking this method up in smaller chunks. (And probably a good idea for readability too!).
+ ]]>
+
+
+
+
+ This method performs arithmetic operations on time values with different units
+ This method {1} performs arithmetic operations on time values with different units
+
+ This method takes two values that appear to be representing time, and performs arithmetic operations on this
+ two values directly, even though it appears that the two values are representing different time units, such as
+ adding a millisecond value to a nanosecond value. You should convert the two values to the same time unit before
+ performing this calculation in order for it to be meaningful.
+ ]]>
+
+
+
+
+ This method needlessly uses a String literal as a Charset encoding
+ This method "{3}" needlessly uses a String literal to define an encoding. A built-in Charset could be used instead like: {4}
+
+ This method uses a string literal to specify a Charset encoding. However the method invoked has an
+ alternative signature that takes a Charset object. You should use this signature, as this class is compiled
+ with JDK 7 (or better), and the Charset in question is available as a constant from the
+ java.nio.charset.StandardCharsets class.
+
So instead of specifying "UTF-8", use StandardCharsets.UTF_8, for instance. An added benefit of this is
+ that you will not need to catch UnsupportedEncodingException.
+ ]]>
+
+
+
+
+ This method should use a StandardCharsets.XXX.name() to specify an encoding
+ This method {3} should use a StandardCharsets.XXX.name() to specify an encoding
+
+ This method uses a hand-typed String literal to specify a Charset encoding. As this class is compiled
+ with JDK 7 (or better), and the charset in question is available as a constant from the
+ java.nio.charset.StandardCharsets class, it is better to use the .name() method of the appropriate
+ StandardCharsets constant.
+
+
The method in question doesn't directly support a Charset as a parameter, only a String.
+ Still, instead of specifying something like "UTF-8" (and potentially mistyping it), use StandardCharsets.UTF_8.name().
+
+ ]]>
+
+
+
+
+ This method uses an unknown character encoding literal
+ This method {3} uses an unknown character encoding literal "{4}"
+
+ This method specifies a Charset encoding with a String literal that is not recognized by the current
+ JDK. It's possible that this application will only be deployed on a JVM that does recognize this encoding, but
+ it seem dubious that this is the case.
+
+ The standard JDK encodings are "UTF-8", "US-ASCII", "ISO-8859-1", "UTF-16BE", "UTF-16LE", "UTF-16". These are all case-sensitive.
+
+ ]]>
+
+
+
+
+ This method uses an excessively complex conditional that can be replaced with Set.contains
+ This method {1} uses an excessively complex conditional that can be replaced with Set.contains
+
+ This method uses an overly complex if expression made up of multiple conditions joined by OR, where the same
+ local variable is compared to a static value. When the number of conditions grow it is much cleaner
+ to build a static set of the possible values, and use the contains method on that set. This will
+ shorten the code, and make it more self documenting.
+ ]]>
+
+
+
+
+ This method is declared more permissively than is used in the code base
+ This method {1} is declared more permissively than is used in the code base
+
+ This method is declared more permissively than the code is using. Having this method be more
+ permissive than is needed limits your ability to make observations about this method, like
+ parameter usage, refactorability, and derivability. It is possible that this detector will report
+ erroneously if:
+
+
The method is called from code not being scanned, such as unit tests
+
The method is an API method, expected to be used by unknown client code
+
The method is called through reflection
+
+
+ ]]>
+
+
+
+
+ This method stores the value of a toString() call into a field
+ This method {0} stores the value of a toString() call into a field
+
+ This method calls the toString() method on an object and stores the value in a field. Doing this
+ throws away the type safety of having the object defined by a Class. Using String makes it very easy to
+ use the wrong type of value, and the compiler will not catch these mistakes. You should delay converting
+ values to Strings for as long as possible, and thus not store them as fields.
+
+ ]]>
+
+
+
+
+ This method parses a String that is a field
+ This method {1} parses a String that is a field
+
+ This method calls a parsing method (indexOf, lastIndexOf, startsWith, endsWith, substring, indexOf) on a String
+ that is a field, or comes from a collection that is a field. This implies that the String in question is holding
+ multiple parts of information inside the string, which would be more maintainable and type safe if that value was a
+ true collection or a first class object with fields, rather than a String.
+
+ ]]>
+
+
+
+
+ This method continues a loop after finding an equality condition
+ This method {1} continues a loop after finding an equality condition
+
+ This method continues with a loop, and does not break out of it, after finding an setting a variable in an if
+ condition based on equality. Since continuing on in the loop would seem to be unlikely to find the item again, breaking
+ at this point would seem to be the proper action.
+ ]]>
+
+
+
+
+ This method accesses URL resources using the File api
+ This method {1} accesses URL resources using the File api]
+
+ This method fetches a resource from a URL, and uses the File api to manipulate it. If this resource is a
+ classpath resource, it will work if the resource is a file in a directory. If however the file is inside a jar file
+ this will fail. Use the URL.openStream api instead to access the data of the classpath resource.
+
+ ]]>
+
+
+
+
+
+ Inefficient String Buffering
+ Synchronized Collection Iterators
+ Cyclomatic Complexity
+ Overly Concrete Parameters
+ List Indexed Iterating
+ Unrelated Collection Contents
+ Declared Runtime Exception
+ Class Envy
+ Literal String Comparison
+ Partially Constructed Object Access
+ Dubious List Collection
+ Parallel Lists
+ Final Parameters
+ Abstract Class Empty Methods
+ Manual Array Copy
+ Floating Point Loops
+ Non Collection Method Use
+ Confusing Autoboxed Overloading
+ Abnormal Finally Block Return
+ Static Method Instance Invocation
+ Spurious Thread States
+ Needless Autoboxing
+ Unnecessary Store Before Return
+ Copied Overridden Method
+ Array Based Collection
+ Orphaned DOM Node
+ Abstract Overridden Method
+ Custom Built XML
+ Bloated Synchronized Block
+ Constant List Index
+ Sloppy Class Reflection
+ Array Wrapped Call By Reference
+ Sluggish GUI
+ Needless Instance Retrieval
+ Double Date comparison
+ Suspicious Wait on Concurrent Object
+ JDBC Vendor Reliance
+ Possible Memory Bloat
+ Local Synchronized Collection
+ Field Could Be Local
+ Non Owned Synchronization
+ Non Recycleable Taglib
+ Section 508 Compliance Violations
+ Use Enum Collections
+ SQL In Loop
+ Needless Member Collection Synchronization
+ Inheritance Type Checking
+ Static Array Created in Method
+ Possibly Redundant Method Calls
+ Use toArray
+ Lost Exception Stack Trace
+ Use Character Parameterized Method
+ Tail Recursion
+ Unrelated Return Values
+ Possible Incomplete Serialization
+ Suspicious Comparator Return Values
+ Sillyness Pot Pourri
+ Bloated Assignment Scope
+ Spoiled Child Interface Implementor
+ Deleting While Iterating
+ Use String Split
+ Suspicious JDK Version Use
+ Use Add All
+ Method Returns Constant
+ Needless Custom Serialization
+ Misleading Overload Model
+ Exception Softening
+ Confusing Function Semantics
+ JUnit Assertion Oddities
+ Suspicious Clone Algorithm
+ Weak Exception Messaging
+ Suspicious Clustered Session Support
+ Logger Oddities
+ Incorrect Internal Class use
+ Dubious Set of Collections
+ Bogus Exception Declaration
+ Unnecessary New Null Check
+ Deprecated Typesafe Enum Pattern
+ Stuttered Method Arguments
+ Tristate Boolean Pattern
+ Suspicious Uninitialized Array
+ Inappropriate toString Use
+ Inconsistent Key Name Casing
+ Overzealous Casting
+ Poorly Defined Parameter
+ Non Symmetric Equals
+ Contravariant Array Assignment
+ Non Functional Field
+ Suspicious Null Guard
+ More Dumb Methods
+ Reflection on Object Methods
+ Improper Properties use
+ Possible Constant Allocation In Loop
+ Write Only Collection
+ Use Var Args
+ Possible Unsuspected Serialization
+ Side Effect Constructor
+ Suspicious Getter Setter Use
+ Lingering Graphics Object
+ Stacked Try Blocks
+ Commons EqualsBuilder To Equals
+ Commons HashCodeBuilder To hashCode
+ Commons ToStringBuilder To String
+ Compare class name equals
+ Backport concurrent reuse of public identifiers
+ Clone Usability
+ Confusing Array asList
+ Presize Collection
+ Unbound Method Template Parameter
+ Non Productive Method Call
+ Array Index Out of Bounds
+ Invalid Constant Argument
+ Collection Naming Confusion
+ Poor Mans Enum
+ Unused Parameter
+ Circular Dependencies
+ Modifying Unmodifiable Collection
+ Unjitable method
+ Hanging ExecutorService
+ HttpClient Problems
+ Conflicting Time Units
+ Charset Issues
+ Contains Based Conditional
+ Overly Permissive Method
+ Class Impersonating String
+ Suspicious Loop Search
+ Conflating Resources And Files
+
\ No newline at end of file
diff --git a/src/main/resources/hudson/plugins/violations/types/findbugs/findbugs-1.3.3-rc2.messages.xml b/src/main/resources/hudson/plugins/violations/types/findbugs/findbugs-3.0.1.messages.xml
similarity index 60%
rename from src/main/resources/hudson/plugins/violations/types/findbugs/findbugs-1.3.3-rc2.messages.xml
rename to src/main/resources/hudson/plugins/violations/types/findbugs/findbugs-3.0.1.messages.xml
index 1685191..be63d16 100644
--- a/src/main/resources/hudson/plugins/violations/types/findbugs/findbugs-1.3.3-rc2.messages.xml
+++ b/src/main/resources/hudson/plugins/violations/types/findbugs/findbugs-3.0.1.messages.xml
@@ -1,15 +1,15 @@
+
-
+ xsi:noNamespaceSchemaLocation="messagecollection.xsd">
- Default FindBugs plugin
+ Core FindBugs plugin
@@ -17,14 +17,80 @@ This plugin contains all of the standard FindBugs detectors.
]]>
+ http://findbugs.sourceforge.net/bugDescriptions.html
+ http://findbugs.sourceforge.net/allBugDescriptions.html
-
+
+ Add msgs (e.g., textual descriptions of bugs) to analysis results
+
+
+ Perform FindBugs Analysis
+
+
+ Launch FindBugs GUI
+
+
+ Convert analysis results to textual form
+
+
+ Provide help for commands
+
+
+ List FindBugs version
+
+
+ Filter analysis results
+
+
+ Set project configuration/options
+
+
+ List details from multi-version analysis results
+
+
+ Merge analysis results from disjoint components
+
+
+ Combine analysis results from different versions of software to produce multi-version analysis results
+
+
+
+ Disassemble a class file
+
+
+ List analysis errors stored in results file
+
+
+
+
+ (cloud disabled)
+ Bug reviews are disabled when using this plugin.
+
+
+ Suppress multithreaded correctness issues
+ Suppress all multithreaded correctness issues
+
+
+ Suppress internationalization issues
+ Suppress all internationalization issues
+
+
+ Suppress internationalization issues in all but selected packages
+ Suppress all internationalization issues except those specified in the i18n.properties resource
+
+
+ Suppress all issues with rank higher than 14
+ Suppress all issues with rank higher than 14
+
+
+ Suppress warnings about vulnerabilities to malicious code
+ Suppress warnings about vulnerabilities to malicious code
+
-
CorrectnessC
@@ -32,28 +98,32 @@ This plugin contains all of the standard FindBugs detectors.
resulting in code that was probably not what the
developer intended. We strive for a low false positive rate.
-
+
+ Bogus random noise
+ N
+ Bogus random noise: intended to be useful
+ as a control in data mining experiments, not in finding actual bugs in software
+
+ SecuritySA use of untrusted input in a way that could create a remotely exploitable security vulnerability.
-
+
-
Bad practiceBViolations of recommended and essential
coding practice. Examples include hash code and equals
- problems, cloneable idiom, dropped exceptions,
+ problems, cloneable idiom, dropped exceptions,
Serializable problems, and misuse of finalize.
We strive to make this analysis accurate,
although some groups may
not care about some of the bad practices.
-
- Dodgy
+ Dodgy codeDcode that is confusing, anomalous, or
written in a way that leads itself to errors.
@@ -64,60 +134,105 @@ This plugin contains all of the standard FindBugs detectors.
In previous versions of FindBugs, this category was known as Style.
-
PerformancePcode that is not necessarily incorrect but may be inefficient
-
Malicious code vulnerabilityVcode that is vulnerable to attacks from untrusted code
-
Multithreaded correctnessMcode flaws having to do with threads, locks, and volatiles
-
InternationalizationIcode flaws having to do with internationalization and locale
-
-
+
+ Experimental
+ X
+ Experimental and not fully vetted bug patterns
+
+
-
-
-
+
+
+ Finds constants which roughly (but not precisely) equal to known values like Math.PI.
+
+]]>
+
+
+
+
+ Finds non-null fields that are not written to in constructors.
+
+]]>
+
+
+
+
+ Finds uses of 32-bit values to describe milliseconds since the epoch.
+
+]]>
+
+
+
+
+ Builds database of parameters that take a 64 bit value describing
+milliseconds since the epoch.
+]]>
+
+
+
+
+ This detector finds inconsistencies between type qualifiers directly
+applied to method parameters and uses of those method parameters.
+]]>
+
+
+
+
+ Finds sequences of operations (e.g., get/put) on a concurrent abstraction
+ that will not be executed atomically.
+
+]]>
+
+
+
+
This detector looks for synchronization on a shared builtin constant (such as a String).
]]>
-
-
-
-
+
+
+
This detector looks for a field that is synchronized on and then null checked.
]]>
-
-
-
+
Looks for violations of the rules for classes annotated as net.jcip.annotations.Immutable.
+
Looks for violations of the rules for classes annotated as net.jcip.annotations.Immutable or javax.annotation.concurrent.Immutable.
]]>
@@ -142,6 +257,20 @@ This plugin contains all of the standard FindBugs detectors.
]]>
+
+
+ Builds the interprocedural call graph.
+ ]]>
+
+
+
+
+ Builds the database of obligation types and methods used by the FindUnsatisfiedObligation detector.
+ ]]>
+
+
Builds of database of all methods defined in analyzed classes, for use
+
Builds a database of all methods defined in analyzed classes, for use
by other detectors.
]]>
@@ -181,30 +310,42 @@ by other detectors.
Builds of database of all methods invoked in analyzed classes, for use
+
Builds a database of all methods invoked in analyzed classes, for use
by other detectors.
]]>
-
+
Looks for potential confusion between inherited and outer methods.
+
Looks for the methods which have no side effect, just return some value.
]]>
-
-
+
Looks for annotations to check return values of a method.
+
Builds the database of string parameters passed from method to method unchanged.
+]]>
+
+
+
+
+ Looks for immutable classes with methods that return new instances of that class,
+where people might accidentally think those methods mutate the instance they are invoked on.
]]>
-
-
-
+
+
+ Looks for potential confusion between inherited and outer methods.
+]]>
+
+
+
Looks for annotations to check return values of a method.
@@ -215,28 +356,27 @@ by other detectors.
Look for code that synchronizes on the results of getClass rather than on class
+
Looks for code that synchronizes on the results of getClass rather than on class
literals.
]]>
-
-
+
- This detector produces summary information for what is stored
- into fields.
+ This detector produces summary information for what is stored
+ into fields.
]]>
-
+
- Looks for @NonNull annotations on methods, fields, and parameters.
+ Looks for @Nonnull annotations on methods, fields, and parameters.
These can be used by the FindNullDeref detector to generate warnings
when a possibly-null value is used in a context where only
non-null values should be used.
@@ -244,9 +384,8 @@ literals.
]]>
-
-
+
Analyze all methods in the application to determine which
@@ -260,19 +399,16 @@ literals.
]]>
-
-
+
Analyze all methods in the application to determine which
- methods always return nonnull values.
+ methods always return non-null values.
]]>
-
-
+
+
+ Looks for methods with Optional return type that return explicit null values.
+
+]]>
+
+
+
+
+ Looks for useless objects.
+]]>
+
+
+
+
+ Looks and warns about mutable enum fields.
+ ]]>
+
+
Looks for uses of this.getClass().getResource(...), which can give
unexpected results if the class is extended by a class in
-another package. /p>
+another package.
]]>
@@ -315,15 +473,6 @@ another package. /p>
]]>
-
-
-
-Looks for an infinite recursive loop. It is a slow detector.
-]]>
-
-
-
]]>
-
]]>
-
-
-
-
-
+
This detector looks for finalizers that null out fields of a class.
+
This detector looks for finalizers that null out fields of a class.
This does not help the garbage collector in any way, the nulling out of fields has no effect.
]]>
-
This detector looks for obvious/blatent cases of cross site scripting vulnerabilities.
+
This detector looks for obvious/blatant cases of cross site scripting vulnerabilities.
+]]>
+
+
+
+
+ This detector looks for code containing repeated conditional tests, such as (x == 5 || x == 5).
+]]>
+
+
+
+
+ This detector looks for code containing useless conditions like the second condition in this expression: (x >= 10 && x >= 5).
+]]>
+
+
+
+
+ This detector looks for calls to methods that are unsupported.
+]]>
+
+
+
+
+ Checks for incorrect format strings.
+
+]]>
+
+
+
+
+ Checks for equals methods that check for their operand being an instance of a class
+that is not compatible with the class defining the equals method.
+
]]>
-
]]>
+
+
+ This detector is just a hook for testing new detectors.
+Normally, this detector does nothing.
+]]>
+
+
+
+
+ This detector finds code that behaves differently under OpenJDK 1.6, where
+weak references are used to hold onto Loggers.
+
+]]>
+
+
+
+
+ This detector is just a hook for testing new detectors.
+Normally, this detector does nothing.
+]]>
+
+
+
+
+ This detector generates a random signal: warnings that are just based on
+hash values of the operations performed by methods.
+These warnings are bogus random noise, intended to be useful
+ as a control in data mining experiments, not in finding actual bugs in software
-
+ This detector is just a hook for testing new detectors.
+Normally, this detector does nothing.
+]]>
+
+
+
+
+ Noisy detector for null dereferences. Intended to be used as a control in experiments
+about the validity or predictive ability of warnings, not as a way to find problems in code.
+
+]]>
+
+
]]>
-
-
-
-
+
Look for code that should be executed inside doPrivileged blocks.
]]>
-
]]>
-
-
]]>
-
]]>
-
]]>
-
]]>
-
| and & instead of
]]>
-
| and & instead of
]]>
-
-
+
+
+ This detector looks for covariant array assignments like Object[] array = new String[10] which may cause ArrayStoreException at runtime.
+
+]]>
+
+
Looks for calls to Number constructors with primitive arguments.
-/p>
+
]]>
-
-
+
This detector looks for instances of double checked locking.
@@ -552,8 +771,7 @@ such as the no-argument String constructor.
]]>
-
-
+
This detector looks for calls to finalize() and other finalizer-related
@@ -561,8 +779,7 @@ issues.
]]>
-
-
+
This detector looks for problems in the definition of the hashCode() and equals()
@@ -570,8 +787,7 @@ methods.
]]>
-
-
+
Looks for equals methods that override equals methods in a superclass where the equivalence relationship might not be symmetrical.
@@ -579,8 +795,7 @@ methods.
]]>
-
-
+
This detector looks for calls to notify() that don't seem
@@ -588,8 +803,7 @@ to modify mutable object state.
]]>
-
-
+
This detector looks for methods that return mutable static data.
@@ -597,8 +811,7 @@ to modify mutable object state.
]]>
-
-
+
This detector looks for calls to Thread.run(). It is a fast
@@ -606,8 +819,7 @@ detector.
]]>
-
-
+
This detector looks for loops that spin reading from a field.
@@ -615,8 +827,7 @@ detector.
]]>
-
-
+
This detector looks for calls to wait() with two (or more) locks held.
@@ -624,8 +835,7 @@ It is a slow detector.
]]>
-
-
+
This detector looks for calls to wait() not in a conditional or loop.
@@ -633,8 +843,7 @@ It is a slow detector.
]]>
-
-
+
This detector looks for reads of uninitialized fields in constructors.
@@ -642,8 +851,7 @@ It is a slow detector.
]]>
-
-
+
This detector looks for get and set methods where the get is unsynchronized
@@ -651,8 +859,7 @@ while the set is synchronized.
]]>
-
-
+
This detector looks for potentially circular class initialization
@@ -660,8 +867,7 @@ dependencies.
]]>
-
-
+
This iterator looks for problems in how Iterator classes are defined.
@@ -669,8 +875,7 @@ dependencies.
]]>
-
-
+
This detector looks for fields that are accessed in an inconsistent manner
@@ -678,8 +883,7 @@ with respect to locking.
]]>
-
-
+
This detector looks for comparisons of String objects using the == or !=
@@ -688,8 +892,7 @@ operators.
]]>
-
-
+
This detector looks for synchronization on objects read from
@@ -697,8 +900,7 @@ modified fields.
]]>
-
-
+
This detector looks for code that seems to be synchronizing on a field in order
@@ -707,8 +909,7 @@ to guard updates of that field.
]]>
-
-
+
This detector looks for static fields that may be modified by
@@ -716,16 +917,14 @@ malicious code.
]]>
-
-
+
This detector looks for suspiciously-named methods.
]]>
-
-
+
This detector looks for calls to InputStream.read() or InputStream.skip() where the
@@ -733,8 +932,7 @@ return value is ignored.
]]>
-
-
+
This detector looks for potential problems in the implementation
@@ -742,16 +940,14 @@ of Serializable classes.
]]>
-
-
+
This detector looks for constructors that start threads.
]]>
-
-
+
This detector looks for incorrect for loops.
@@ -759,15 +955,23 @@ of Serializable classes.
]]>
-
+
+
+ Looks for explicit serialization via readObject and
+ writeObject as evidence
+that this class is, indeed, serialized.
+]]>
+
+
+
This detector looks for fields whose value is never read.
]]>
-
-
+
This detector looks for calls to wait() that are not in a loop.
@@ -775,8 +979,7 @@ of Serializable classes.
]]>
-
-
+
This detector looks for calls to methods where the return value
@@ -784,7 +987,13 @@ is suspiciously ignored. It is a slow detector.
]]>
-
+
+
+ This detector looks for problems in Comparator.compare or Comparable.compareTo implementation.
+]]>
+
+
]]>
-
+
+
+ This detector looks for places where a null pointer exception might
+occur, and the use of non-short-circuit evaluation causes the usual techniques to fail.
+
+]]>
+
+
]]>
-
-
-
]]>
-
-
]]>
-
-
+
This detector looks for empty synchronized blocks.
]]>
-
-
+
This detector looks for fields that are accessed in an inconsistent manner
@@ -873,7 +1083,6 @@ with respect to locking. It is a slow detector.
]]>
-
]]>
-
]]>
-
]]>
-
]]>
-
]]>
-
]]>
-
+
+
+ This detector looks for objects initialized within loop which can be moved outside for better performance.
+
+]]>
+
+
+
+
+ This detector looks for code that uses String.indexOf(String) or String.lastIndexOf(String),
+passing a constant string of length 1. It is recommended to use the more efficient integer implementations.
+A fast detector.
+
+]]>
+
+
-
-
]]>
-
-
]]>
-
This detector looks for Applet constructors that call methods in the parent
Applet that rely on the Applet stub. Since this stub isn't initialized until just
-before the init() method, these methods will fail in the constructor.
-
-]]>
-
-
-
-
-
-
-This detector looks calls to equals(java.lang.Object) on arrays, or final classes that do not
-override the equals method in the Object class. This means that equals semantics is the same as
-==, and probably a mistake.
+before the init() method, these methods will fail in the constructor.
]]>
@@ -1011,9 +1215,8 @@ is always called on the current thread.
]]>
-
-
-
+
+
This detector uses data flow analysis to look for invocations of execute methods
@@ -1022,9 +1225,8 @@ on SQL statements in switch something other than a constant string is passed as
]]>
-
-
-
+
+
This detector looks for assignments to local variables that
@@ -1033,7 +1235,6 @@ are never subsequently read. It is a moderately fast detector.
]]>
-
-
]]>
-
]]>
-
-
+
This detector looks for catch clauses that catch Exception,
when no code in the block throws Exception.
]]>
-
-
+
Looks for floating point equality expressions. A fast detector.
]]>
-
]]>
-
]]>
-
]]>
-
]]>
-
]]>
-
-
]]>
-
This detector looks for places where the result of integer division is
cast to double. Often, what was meant was to cast the integer operands
-to double and then perform the division.
+to double and then perform the division.
]]>
-
+
-This detector looks for bad casts of object references.
+This detector looks for bad casts of object references using data flow analysis.
]]>
-
-
+
-This detector looks for bad casts of object references using data flow analysis.
+This detector looks for stores of non Serializable objects into HTTP sessions.
]]>
-
+
-This detector looks for stores of non Serializable objects into Http sessions.
+This detector looks for uses of of non Serializable objects in contexts that require them to be serializable.
]]>
+
+
-This detector looks for stores of non Serializable objects passed to the writeObject method of
+This detector looks for non Serializable objects passed to the writeObject method of
an ObjectOutput.
]]>
@@ -1199,7 +1389,6 @@ an ObjectOutput.
-
-
-
+
This detector looks for calls to Thread.sleep() made with
@@ -1228,7 +1416,6 @@ their work on Programming Puzzlers.
]]>
-
]]>
-
-
+
This detector looks for internal classes that write to member variables of the
owning class, when that member variable is private. In this case, a special compiler
@@ -1251,9 +1437,8 @@ visibility to protected will allow the field to be directly written.
]]>
-
-
+
This detector looks for direct allocations of implementations of XML interfaces.
This ties the code to a specific implementation, rather than using the supplied
@@ -1262,23 +1447,8 @@ factory pattern to create these objects.
]]>
-
-
-
-
- This detector looks for equals(Object) method implementations which
- unconditionally dereference their parameter. This violates the contract
- defined by java.lang.Object.equals(), which states that if the parameter
- is null, the method must return null.
-
-
It is a slow detector.
- ]]>
-
-
-
-
+
This detector looks for subclasses that implement methods defined in the super
@@ -1289,9 +1459,8 @@ factory pattern to create these objects.
]]>
-
-
+
This detector for final classes that declare protected members. As this
@@ -1305,21 +1474,19 @@ factory pattern to create these objects.
]]>
-
-
+
- This detector looks for simple assignments of literal boolean values to variables in
+ This detector looks for simple assignments of literal boolean values to variables in
conditional expressions.
]]>
-
-
+
TrainNullReturnValues determines which methods may return null and saves
@@ -1333,9 +1500,8 @@ factory pattern to create these objects.
]]>
-
-
+
TrainUnconditionalParamDerefs determines which methods may
@@ -1350,9 +1516,8 @@ factory pattern to create these objects.
]]>
-
-
+
TrainFieldStoreTypes analyzes the types stored into fields
@@ -1365,27 +1530,24 @@ factory pattern to create these objects.
]]>
-
-
+
- TrainNonNullAnnotations collects @NonNull and @PossiblyNull annotations
+ TrainNonNullAnnotations collects @Nonnull and @PossiblyNull annotations
and stores them to database files. This is a fast detector.
]]>
-
-
+
This detector is just for debugging method call resolution in FindBugs.
Don't enable it.
]]>
-
]]>
-
]]>
-
This detector looks at the arguments of calls to generic
- container methods that receive a java.lang.Object
- to see if the argument's type is related to the container's
- parameter. Arguments with unrelated class types are never going
- to be in the container. For example, if foo is a
- List<String> and bar is a
+
This detector looks at the arguments of calls to generic
+ collection methods that receive a java.lang.Object
+ to see if the argument's type is related to the collection's
+ parameter. Arguments with unrelated class types are never going
+ to be in the collection. For example, if foo is a
+ List<String> and bar is a
StringBuffer, the call foo.contains(bar)
- will always return false. This is a fast detector.
+ will always return false. This is a fast detector.
]]>
-
-
-
+
+
This detector warns about static fields of type java.util.Calendar or java.text.DateFormat (and subclasses) because
Calendars are inherently unsafe for multithreaded use.
]]>
-
-
+
This is an internal detector used only for testing dataflow analyses.
- It is not enabled by default.
+
This is an internal detector used only for testing dataflow analyses.
+ It is not enabled by default.
]]>
-
]]>
-
+
Looks for an attempt to append to an object output stream
]]>
+
+
+ Checks @ExpectedWarning and @NoWarning annotations.
+ This detector is used only for testing FindBugs.
+ ]]>
+
+
+
+
+ Checks that if the result of putIfAbsent is ignored,
+ the value passed as the second argument is not reused.
+ ]]>
+
+
+
+
+ Checks for methods invoked from constructors for superclasses.
+ ]]>
+
+
+
+
+ Checks for calls to methods which perform a byte to String (or String to byte) conversion using the user's default
+ platform encoding. This can cause the application behaviour to vary between platforms.
+]]>
+
+
+
+
+ Checks that overriding methods do not relax @Nonnull (made @CheckForNull) on return values
+ or @CheckForNull (made @Nonnull) on parameters.
+ ]]>
+
+
+
+ Rough value of known constant found
+ Rough value of {3} found: {2}
+
+ It's recommended to use the predefined library constant for code clarity and better precision.
+]]>
+
+
+
+ Class too big for analysis
+ {0} is too big for analysis
+
+ This class is bigger than can be effectively handled, and was not fully analyzed for errors.
+
+]]>
+
+
+
+ Bogus warning about a null pointer dereference
+ Bogus warning about a null pointer dereference in {1}
+
+ Bogus warning.
+]]>
+
+
+
+ Bogus warning about a method call
+ Bogus warning about a method call {2} in {1}
+
+ Bogus warning.
+]]>
+
+
+
+ Bogus warning about a field reference
+ Bogus warning about a reference to {2} in {1}
+
+ Bogus warning.
+]]>
+
+
+
+ Bogus warning about an operation
+ Bogus warning about an operation {1}
+
+ Bogus warning.
+]]>
+
+
+
+ BigDecimal constructed from double that isn't represented precisely
+ BigDecimal constructed from {4} in {1}
+
+
+This code creates a BigDecimal from a double value that doesn't translate well to a
+decimal number.
+For example, one might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625.
+You probably want to use the BigDecimal.valueOf(double d) method, which uses the String representation
+of the double to create the BigDecimal (e.g., BigDecimal.valueOf(0.1) gives 0.1).
+
+
+]]>
+
+
+
+
+ D'oh! A nonsensical method invocation
+ D'oh! A nonsensical invocation of {2.nameAndSignature} in {1}
+
+
+This partical method invocation doesn't make sense, for reasons that should be apparent from inspection.
+
+
+]]>
+
+
+
+
+ Useless/vacuous call to EasyMock method
+ Useless/vacuous call to {2} in {1}
+
+ This call doesn't pass any objects to the EasyMock method, so the call doesn't do anything.
+
+
+]]>
+
+
+
+ Creation of ScheduledThreadPoolExecutor with zero core threads
+ Creation of ScheduledThreadPoolExecutor with zero core threads in {1}
+
+ (Javadoc)
+A ScheduledThreadPoolExecutor with zero core threads will never execute anything; changes to the max pool size are ignored.
+
+
+]]>
+
+
+
+ Futile attempt to change max pool size of ScheduledThreadPoolExecutor
+ Futile attempt to change max pool size of ScheduledThreadPoolExecutor in {1}
+
+ (Javadoc)
+While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect.
+
+
+]]>
+
+
+
+ Call to unsupported method
+ Call to unsupported method {2} in {1}
+
+ All targets of this method invocation throw an UnsupportedOperationException.
+
+
+]]>
+
+ Empty database passwordEmpty database password in {1}
This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password.
+
This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password.
]]>
@@ -1477,99 +1805,147 @@ factory pattern to create these objects.
Hardcoded constant database password in {1}
This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can
- easily learn the password.
+
This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can
+ easily learn the password.
]]>
-
-
HTTP cookie formed from untrusted inputHTTP cookie formed from untrusted input in {1}
This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting
+
This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting
vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting
for more information.
-
FindBugs looks only for the most blatent, obvious cases of HTTP response splitting.
-If FindBugs found any, you almostly certainly have more
-vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously
-consider using a commercial static analysis or pen-testing tool, such as those provided by Fortify Software,
-a sponsor of the FindBugs project. If your software is open source, Fortify will scan your code for free
-as part of the JOR (Java Open Review) effort.
+
FindBugs looks only for the most blatant, obvious cases of HTTP response splitting.
+If FindBugs found any, you almost certainly have more
+vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously
+consider using a commercial static analysis or pen-testing tool.
]]>
-
-
- HTTP Response splitting vulnerability
- HTTP parameter directly written to HTTP header output in {1}
-
+
+ HTTP Response splitting vulnerability
+ HTTP parameter directly written to HTTP header output in {1}
+
This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP response splitting
+
FindBugs looks only for the most blatent, obvious cases of HTTP response splitting.
-If FindBugs found any, you almostly certainly have more
-vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously
-consider using a commercial static analysis or pen-testing tool, such as those provided by Fortify Software,
-a sponsor of the FindBugs project. If your software is open source, Fortify will scan your code for free
-as part of the JOR (Java Open Review) effort.
+
FindBugs looks only for the most blatant, obvious cases of HTTP response splitting.
+If FindBugs found any, you almost certainly have more
+vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously
+consider using a commercial static analysis or pen-testing tool.
]]>
-
+
+
+
+
+
+ Relative path traversal in servlet
+ Relative path traversal in {1}
+
+The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.
+
+See http://cwe.mitre.org/data/definitions/23.html
+for more information.
+
FindBugs looks only for the most blatant, obvious cases of relative path traversal.
+If FindBugs found any, you almost certainly have more
+vulnerabilities that FindBugs doesn't report. If you are concerned about relative path traversal, you should seriously
+consider using a commercial static analysis or pen-testing tool.
+
+
+]]>
+
+
+
+ Absolute path traversal in servlet
+ Absolute path traversal in {1}
+
+The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory,
+but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory.
+
+See http://cwe.mitre.org/data/definitions/36.html
+for more information.
+
FindBugs looks only for the most blatant, obvious cases of absolute path traversal.
+If FindBugs found any, you almost certainly have more
+vulnerabilities that FindBugs doesn't report. If you are concerned about absolute path traversal, you should seriously
+consider using a commercial static analysis or pen-testing tool.
+
+
+]]>
+
+
+
Servlet reflected cross site scripting vulnerability
- HTTP parameter directly written to Servlet output, giving reflected XSS vulnerability in {1}
-
+ HTTP parameter written to Servlet output in {1}
+
This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting
+
This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting
vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting
for more information.
-
FindBugs looks only for the most blatent, obvious cases of cross site scripting.
-If FindBugs found any, you almostly certainly have more cross site scripting
-vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously
-consider using a commercial static analysis or pen-testing tool, such as those provided by Fortify Software,
-a sponsor of the FindBugs project. If your software is open source, Fortify will scan your code for free
-as part of the JOR (Java Open Review) effort.
+
FindBugs looks only for the most blatant, obvious cases of cross site scripting.
+If FindBugs found any, you almost certainly have more cross site scripting
+vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously
+consider using a commercial static analysis or pen-testing tool.
]]>
+
+
+ Servlet reflected cross site scripting vulnerability in error page
+ HTTP parameter written to Servlet error page in {1}
+
+This code directly writes an HTTP parameter to a Server error page (using HttpServletResponse.sendError). Echoing this untrusted input allows
+for a reflected cross site scripting
+vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting
+for more information.
+
FindBugs looks only for the most blatant, obvious cases of cross site scripting.
+If FindBugs found any, you almost certainly have more cross site scripting
+vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously
+consider using a commercial static analysis or pen-testing tool.
+
+
+]]>
+
+ JSP reflected cross site scripting vulnerabilityHTTP parameter directly written to JSP output, giving reflected XSS vulnerability in {1.class}
-
+
This code directly writes an HTTP parameter to JSP output, which allows for a cross site scripting
+
FindBugs looks only for the most blatent, obvious cases of cross site scripting.
-If FindBugs found any, you almostly certainly have more cross site scripting
-vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously
-consider using a commercial static analysis or pen-testing tool, such as those provided by Fortify Software,
-a sponsor of the FindBugs project. If your software is open source, Fortify will scan your code for free
-as part of the JOR (Java Open Review) effort.
+
FindBugs looks only for the most blatant, obvious cases of cross site scripting.
+If FindBugs found any, you almost certainly have more cross site scripting
+vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously
+consider using a commercial static analysis or pen-testing tool.
]]>
-
Certain swing methods needs to be invoked in Swing threadCall to swing method in {1} needs to be performed in Swing event thread
(From JDC Tech Tip): The Swing methods
+
(From JDC Tech Tip): The Swing methods
show(), setVisible(), and pack() will create the associated peer for the frame.
With the creation of the peer, the system creates the event dispatch thread.
This makes things problematic because the event dispatch thread could be notifying
@@ -1582,8 +1958,6 @@ visible), they could trigger listener notification on the event dispatch thread.
]]>
-
-
An apparent infinite loopThere is an apparent infinite loop in {1}
@@ -1594,7 +1968,6 @@ throwing an exception).
]]>
-
An apparent infinite recursive loopThere is an apparent infinite recursive loop in {1}
@@ -1605,23 +1978,17 @@ an infinite recursive loop that will result in a stack overflow.
]]>
-
-
- A container is added to itself
- A container is added to itself in {1}
+ A collection is added to itself
+ A collection is added to itself in {1}
A container is added to itself. As a result, computing the hashCode of this
+
A collection is added to itself. As a result, computing the hashCode of this
set will throw a StackOverflowException.
]]>
-
-
-
-
A volatile reference to an array doesn't treat the array elements as volatile{1} is a volatile reference to an array; the array elements are non-volatile
@@ -1636,7 +2003,18 @@ in Java 5.0).
]]>
-
+
+ An increment to a volatile field isn't atomic
+ Increment of volatile field {2} in {1}
+
+This code increments a volatile field. Increments of volatile fields aren't
+atomic. If more than one thread is incrementing the field at the same time,
+increments could be lost.
+
+]]>
+
+ Usage of GetResource may be unsafe if class is extendedUsage of GetResource in {1} may be unsafe if class is extended
@@ -1648,39 +2026,70 @@ another package.
]]>
-
-
- Method with Boolean return type returns explicit null
- {1} has Boolean return type and returns explicit null
-
-
- A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen.
- This method can be invoked as though it returned a value of type boolean, and
- the compiler will insert automatic unboxing of the Boolean value. If a null value is returned,
- this will result in a NullPointerException.
-
- ]]>
-
-
-
-
-
- Synchronize and null check on the same field.
- In {1} the field {2.givenClass} is synchronized on and then checked if null.
-
+ Method with Boolean return type returns explicit null
+ {1} has Boolean return type and returns explicit null
+
+
+ A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen.
+ This method can be invoked as though it returned a value of type boolean, and
+ the compiler will insert automatic unboxing of the Boolean value. If a null value is returned,
+ this will result in a NullPointerException.
+
+ ]]>
+
+
+
+ Method with Optional return type returns explicit null
+ {1} has Optional return type and returns explicit null
+
+
+ The usage of Optional return type (java.util.Optional or com.google.common.base.Optiona)
+ always mean that explicit null returns were not desired by design.
+ Returning a null value in such case is a contract violation and will most likely break clients code.
+
+ ]]>
+
+
+
+ Non-null field is not initialized
+ Non-null field {2.name} is not initialized by {1}
+
+ The field is marked as non-null, but isn't written to by the constructor.
+ The field might be initialized elsewhere during constructor, or might always
+ be initialized before use.
+
+ ]]>
+
+
+
+ Synchronize and null check on the same field.
+ In {1} the field {2.givenClass} is synchronized on and then checked if null.
+
Since the field is synchronized on, it seems not likely to be null.
If it is null and then synchronized on a NullPointerException will be
-thrown and the check would be pointless. Better to synchronize on
+thrown and the check would be pointless. Better to synchronize on
another field.
]]>
-
-
-
+
+
+ Repeated conditional tests
+ Repeated conditional test in {1}
+
+The code contains a conditional test is performed twice, one right after the other
+(e.g., x == 0 || x == 0). Perhaps the second occurrence is intended to be something else
+(e.g., x == 0 || y == 0).
+
+]]>
+
+ TestingTest warning generated in {1}
@@ -1688,6 +2097,36 @@ another field.
This bug pattern is only generated by new, incompletely implemented
bug detectors.
+]]>
+
+
+
+ Testing 1
+ Test warning 1 generated in {1}
+
+This bug pattern is only generated by new, incompletely implemented
+bug detectors.
+]]>
+
+
+
+ Testing 2
+ Test warning 2 generated in {1}
+
+This bug pattern is only generated by new, incompletely implemented
+bug detectors.
+]]>
+
+
+
+ Testing 3
+ Test warning 3 generated in {1}
+
+This bug pattern is only generated by new, incompletely implemented
+bug detectors.
]]>
@@ -1703,8 +2142,6 @@ or perhaps if an analysis was generated using a plugin, but that plugin is not c
]]>
-
-
Creates an empty zip file entryEmpty zip file entry created in {1}
@@ -1719,7 +2156,6 @@ should be written to the ZipFile between the calls to
]]>
-
Creates an empty jar file entryEmpty jar file entry created in {1}
@@ -1734,7 +2170,6 @@ should be written to the JarFile between the calls to
]]>
-
Dubious catching of IllegalMonitorStateExceptionDubious catching of IllegalMonitorStateException in {1}
@@ -1746,8 +2181,6 @@ should be written to the JarFile between the calls to
]]>
-
-
Method performs math using floating point precision{1} performs math using floating point precision
@@ -1760,7 +2193,61 @@ should be written to the JarFile between the calls to
]]>
-
+
+ Covariant array assignment to a field
+ Array of type {2} is assigned to the field of type {3}
+
+Array of covariant type is assigned to a field. This is confusing and may lead to ArrayStoreException at runtime
+if the reference of some other type will be stored in this array later like in the following code:
+
+
Number[] arr = new Integer[10];
+arr[0] = 1.0;
+
+
Consider changing the type of created array or the field type.
+]]>
+
+
+
+ Covariant array assignment to a local variable
+ Array of type {2} is assigned to the variable of type {3}
+
+Array of covariant type is assigned to a local variable. This is confusing and may lead to ArrayStoreException at runtime
+if the reference of some other type will be stored in this array later like in the following code:
+
+
Number[] arr = new Integer[10];
+arr[0] = 1.0;
+
+
Consider changing the type of created array or the local variable type.
+]]>
+
+
+
+ Covariant array is returned from the method
+ Array of type {2} is returned from the method which return type is {3}
+
+Array of covariant type is returned from the method. This is confusing and may lead to ArrayStoreException at runtime
+if the calling code will try to store the reference of some other type in the returned array.
+
+
Consider changing the type of created array or the method return type.
+]]>
+
+
+
+ Possibly incompatible element is stored in covariant array
+ Value of type {2} is stored into array which element type is {3}
+
+Value is stored into the array and the value type doesn't match the array type.
+It's known from the analysis that actual array type is narrower than the declared type of its variable or field
+and this assignment doesn't satisfy the original array type. This assignment may cause ArrayStoreException
+at runtime.
+
+]]>
+
+ Class implements Cloneable but does not define or use clone methodClass {0} implements Cloneable but does not define or use clone method
@@ -1772,20 +2259,18 @@ should be written to the JarFile between the calls to
]]>
-
Class defines clone() but doesn't implement Cloneable{0} defines clone() but doesn't implement Cloneable
This class defines a clone() method but the class doesn't implement Cloneable.
-There are some situations in which this is OK (e.g., you want to control how subclasses
+There are some situations in which this is OK (e.g., you want to control how subclasses
can clone themselves), but just make sure that this is what you intended.
]]>
-
clone method does not call super.clone(){1} does not call super.clone()
@@ -1802,33 +2287,29 @@ to use Object.clone(), which always returns an object of the correct type.
]]>
-
-
Use of identifier that is a keyword in later versions of Java{1} uses {2} for a variable name, which is a keyword in later versions of Java
The identifier is a word that is reserversed as a keyword in later versions of Java, and your code will need to be changed
+
The identifier is a word that is reserved as a keyword in later versions of Java, and your code will need to be changed
in order to compile it in later versions of Java.
]]>
-
+ Use of identifier that is a keyword in later versions of Java{1} conflicts with a keyword in a more recent version of Java
This identifier is used as a keyword in later versions of Java. This code, and
-any code that references this API,
-will need to be changed in order to compile it in later versions of Java.
+
This identifier is used as a keyword in later versions of Java. This code, and
+any code that references this API,
+will need to be changed in order to compile it in later versions of Java.
]]>
-
-
Method might drop exception{1} might drop {2}
@@ -1851,10 +2332,9 @@ will need to be changed in order to compile it in later versions of Java.
]]>
-
-
+ Method invoked that should be only be invoked inside a doPrivileged block
- {1} invokes {2}, which should be invoked from within a doPrivileged block
+ Invocation of {2}, which should be invoked from within a doPrivileged block, in {1}
This code invokes a method that requires a security permission check.
@@ -1863,9 +2343,10 @@ will need to be changed in order to compile it in later versions of Java.
]]>
-
+
+
Method invoked that should be only be invoked inside a doPrivileged block
- {1} invokes {2}, which should be invoked from within a doPrivileged block
+ Invocation of {2}, which should be invoked from within a doPrivileged block, in {1}
This code invokes a method that requires a security permission check.
@@ -1874,48 +2355,34 @@ will need to be changed in order to compile it in later versions of Java.
]]>
-
-
+ Classloaders should only be created inside doPrivileged block{1} creates a {2} classloader, which should be performed within a doPrivileged block
This code creates a classloader, which requires a security manager.
- If this code will be granted security permissions, but might be invoked by code that does not
- have security permissions, then the classloader creation needs to occur inside a doPrivileged block.
+
This code creates a classloader, which needs permission if a security manage is installed.
+ If this code might be invoked by code that does not
+ have security permissions, then the classloader creation needs to occur inside a doPrivileged block.
]]>
-
- Classloaders should only be created inside doPrivileged block
- {1} creates a {2} classloader, which should be performed within a doPrivileged block
-
- This code creates a classloader, which requires a security manager.
- If this code will be granted security permissions, but might be invoked by code that does not
- have security permissions, then the classloader creation needs to occur inside a doPrivileged block.
-]]>
-
-
-
Fields of immutable classes should be final{1.givenClass} should be final since {0} is marked as Immutable.
The class is annotated with net.jcip.annotations.Immutable, and the rules for that annotation require
-that all fields are final.
+
The class is annotated with net.jcip.annotations.Immutable or javax.annotation.concurrent.Immutable,
+ and the rules for those annotations require that all fields are final.
.
]]>
-
Thread passed where Runnable expectedThread passed where Runnable expected in {1}
A Thread object is passed as a parameter to a method where
+
A Thread object is passed as a parameter to a method where
a Runnable is expected. This is rather unusual, and may indicate a logic error
or cause unexpected behavior.
@@ -1937,7 +2404,7 @@ Consider using java.net.URI instead.
The equals and hashCode methods of URL are blocking
- {1} invokes {2}, which blocks to do domain name resolution
+ Invocation of {2}, which blocks to do domain name resolution, in {1}
The equals and hashCode
@@ -1949,19 +2416,16 @@ Consider using java.net.URI instead.
- Can't use reflection to check for presence of annotation with default retention
- {1} uses reflection to check for the presence of an annotation that has default retention
+ Can't use reflection to check for presence of annotation without runtime retention
+ Use of reflection to check for the presence the annotation {3} which doesn't have runtime retention, in {1}
Unless an annotation has itself been annotated with a @Retention other than the default
-of source-only retention, the annotation isn't retained in the classfile and can't be observed using reflection
- (e.g., by using the isAnnotationPresent method).
+
Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME), the annotation can't be observed using reflection
+(e.g., by using the isAnnotationPresent method).
.
]]>
-
-
Method invokes System.exit(...){1} invokes System.exit(...), which shuts down the entire virtual machine
@@ -1974,10 +2438,8 @@ of source-only retention, the annotation isn't retained in the classfile and can
]]>
-
-
- Method invokes dangerous method runFinalizersOnExit
+ Method invokes dangerous method runFinalizersOnExit{1} invokes dangerous method runFinalizersOnExit
-- Joshua Bloch
]]>
-
Method invokes inefficient new String(String) constructor{1} invokes inefficient new String(String) constructor
@@ -2000,8 +2461,6 @@ dangerous methods in the Java libraries. -- Joshua Bloch
]]>
-
-
Method invokes inefficient new String() constructor{1} invokes inefficient new String() constructor
@@ -2018,7 +2477,7 @@ dangerous methods in the Java libraries. -- Joshua Bloch
Method invokes toString() method on a String
- Method {1} invokes toString() method on a String
+ {1} invokes toString() method on a String
Calling String.toString() is just a redundant operation.
@@ -2053,10 +2512,9 @@ dangerous methods in the Java libraries. -- Joshua Bloch
]]>
-
Method invokes inefficient Number constructor; use static valueOf instead
- Method {1} invokes inefficient {2} constructor; use {3} instead
+ {1} invokes inefficient {2} constructor; use {3} instead
@@ -2079,7 +2537,7 @@ dangerous methods in the Java libraries. -- Joshua Bloch
Method invokes inefficient floating-point Number constructor; use static valueOf instead
- Method {1} invokes inefficient {3} constructor; use {4} instead
+ {1} invokes inefficient {2} constructor; use {3} instead
@@ -2094,31 +2552,21 @@ dangerous methods in the Java libraries. -- Joshua Bloch
]]>
-
-
- Method invokes inefficient String.equals(""); use String.length() == 0 instead
- Method {1} invokes inefficient String.equals(""); use String.length() == 0 instead
-
- An object is compared to the empty String object using the equals() method here.
- Checking that the String object's length is zero may be faster, and removes String constants from the class file.
-]]>
-
- Consider using Locale parameterized version of invoked method
- Use of non-localized String.toUpperCase() or String.toLowerCase
+ Use of non-localized String.toUpperCase() or String.toLowerCase() in {1}
A String is being converted to upper or lowercase, using the platform's default encoding. This may
result in improper conversions when used with international characters. Use the
-
String.toUpperCase( Locale l )
String.toLowerCase( Locale l )
+
+
String.toUpperCase( Locale l )
+
String.toLowerCase( Locale l )
+
versions instead.
]]>
-
-
Primitive value is unboxed and coerced for ternary operatorPrimitive value is unboxed and coerced for ternary operator in {1}
@@ -2127,8 +2575,8 @@ dangerous methods in the Java libraries. -- Joshua Bloch
A wrapped primitive value is unboxed and converted to another primitive type as part of the
evaluation of a conditional ternary operator (the b ? e1 : e2 operator). The
semantics of Java mandate that if e1 and e2 are wrapped
-numeric values, the values are unboxed and converted/coerced to their common type (e.g,
-if e1 is of type Integer
+numeric values, the values are unboxed and converted/coerced to their common type (e.g,
+if e1 is of type Integer
and e2 is of type Float, then e1 is unboxed,
converted to a floating point value, and boxed. See JLS Section 15.25.
@@ -2141,21 +2589,28 @@ converted to a floating point value, and boxed. See JLS Section 15.25.
A primitive is boxed, and then immediately unboxed. This probably is due to a manual
- boxing in a place where an unboxed value is required, thus forcing the compiler
+ boxing in a place where an unboxed value is required, thus forcing the compiler
to immediately undo the work of the boxing.
]]>
-
-
-
+
+ Boxed value is unboxed and then immediately reboxed
+ Boxed value is unboxed and then immediately reboxed in {1}
+
+A boxed value is unboxed and then immediately reboxed.
+
+]]>
+
+ Primitive value is boxed then unboxed to perform primitive coercionPrimitive value is boxed then unboxed to perform primitive coercion in {1}
A primitive boxed value constructed and then immediately converted into a different primitive type
+
A primitive boxed value constructed and then immediately converted into a different primitive type
(e.g., new Double(d).intValue()). Just perform direct primitive coercion (e.g., (int) d).
]]>
@@ -2180,11 +2635,30 @@ to immediately undo the work of the boxing.
]]>
-
-
+
+ Boxing/unboxing to parse a primitive
+ Boxing/unboxing to parse a primitive {1}
+
+A boxed primitive is created from a String, just to extract the unboxed primitive value.
+ It is more efficient to just call the static parseXXX method.
+]]>
+
+
+
+ Boxing a primitive to compare
+ Primitive is boxed to call {2}: use {3} instead
+
+A boxed primitive is created just to call compareTo method. It's more efficient to use static compare method
+ (for double and float since Java 1.4, for other primitive types since Java 1.7) which works on primitives directly.
+
+]]>
+
+ Method allocates an object, only to get the class object
- Method {1} allocates an object, only to get the class object
+ {1} allocates an object, only to get the class object
This method allocates an object just to call getClass() on it, in order to
@@ -2192,11 +2666,10 @@ to immediately undo the work of the boxing.
]]>
-
- Monitor wait() called on Condition
- Monitor wait() called on a Condition in {1}
-
+ Monitor wait() called on Condition
+ Monitor wait() called on a Condition in {1}
+
This method calls wait() on a
@@ -2207,10 +2680,9 @@ to immediately undo the work of the boxing.
]]>
-
Random value from 0 to 1 is coerced to the integer 0
- Method {1} uses generates a random value from 0 to 1 and then coerces that value to the integer 0
+ {1} uses generates a random value from 0 to 1 and then coerces that value to the integer 0
A random value from 0 to 1 is being coerced to the integer value 0. You probably
@@ -2219,27 +2691,37 @@ want to multiple the random value by something else before coercing it to an int
]]>
-
+
+ Incorrect combination of Math.max and Math.min
+ Incorrect combination of Math.max and Math.min: this code always returns {2}
+
+This code tries to limit the value bounds using the construct like Math.min(0, Math.max(100, value)). However the order of
+ the constants is incorrect: it should be Math.min(100, Math.max(0, value)). As the result this code always produces the same result
+ (or NaN if the value is NaN).
+]]>
+
+ Use the nextInt method of Random rather than nextDouble to generate a random integer
- Method {1} uses the nextDouble method of Random to generate a random integer; using nextInt is more efficient
+ {1} uses the nextDouble method of Random to generate a random integer; using nextInt is more efficient
If r is a java.util.Random, you can generate a random number from 0 to n-1
using r.nextInt(n), rather than using (int)(r.nextDouble() * n).
+
The argument to nextInt must be positive. If, for example, you want to generate a random
+value from -99 to 0, use -r.nextInt(100).
+
]]>
-
-
-
- Nonconstant string passed to execute method on an SQL statement
- Method {1} passes a nonconstant String to an execute method on an SQL statement
+ Nonconstant string passed to execute or addBatch method on an SQL statement
+ {1} passes a nonconstant String to an execute or addBatch method on an SQL statement
The method invokes the execute method on an SQL statement with a String that seems
+
The method invokes the execute or addBatch method on an SQL statement with a String that seems
to be dynamically generated. Consider using
a prepared statement instead. It is more efficient and less vulnerable to
SQL injection attacks.
@@ -2247,10 +2729,9 @@ SQL injection attacks.
]]>
-
A prepared statement is generated from a nonconstant String
- A prepared statement is generated from a nonconstant String at {1}
+ A prepared statement is generated from a nonconstant String in {1}
The code creates an SQL prepared statement from a nonconstant String.
@@ -2260,10 +2741,9 @@ be used to make the prepared statement do something unexpected and undesirable.
]]>
-
A thread was created using the default empty run method
- Method {1} creates a thread using the default empty run method
+ {1} creates a thread using the default empty run method
This method creates a thread without specifying a run method either by deriving from the Thread class, or
@@ -2272,7 +2752,6 @@ be used to make the prepared statement do something unexpected and undesirable.
]]>
-
Possible double check of fieldPossible doublecheck on {2} in {1}
@@ -2286,29 +2765,41 @@ be used to make the prepared statement do something unexpected and undesirable.
]]>
-
+
+ Possible exposure of partially initialized object
+ Possible exposure of partially initialized object in {1}
+
+Looks like this method uses lazy field initialization with double-checked locking.
+ While the field is correctly declared as volatile, it's possible that the internal structure of
+ the object is changed after the field assignment, thus another thread may see the partially initialized object.
+
To fix this problem consider storing the object into the local variable first
+ and save it to the volatile field only after it's fully constructed.
+
+]]>
+
+ Finalizer nulls fields
- {3} is set to null inside finalize method
-
+ {3} is set to null inside finalize method in {1.class}
+
This finalizer nulls out fields. This is usually an error, as it does not aid garbage collection,
- and the object is going to be garbage collected anyway.
+ and the object is going to be garbage collected anyway.
]]>
-
-
+
+ Finalizer only nulls fields{1} only nulls fields
-
+
This finalizer does nothing except null out fields. This is completely pointless, and requires that
the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize
-method.
+method.
]]>
-
-
-
+
+ Finalizer should be protected, not public{1} is public; should be protected
@@ -2319,7 +2810,6 @@ method.
]]>
-
Empty finalizer should be deleted{1} is empty and should be deleted
@@ -2330,7 +2820,6 @@ method.
]]>
-
Finalizer nullifies superclass finalizer{1} is nullifying {2}.finalize(); is this intended?
@@ -2343,7 +2832,6 @@ method.
]]>
-
Finalizer does nothing but call superclass finalizer{1} does nothing except call super.finalize(); delete it
@@ -2355,7 +2843,6 @@ method.
]]>
-
Finalizer does not call superclass finalizer{1} missing call to super.finalize(), so {2}.finalize() doesn't get called
@@ -2368,10 +2855,9 @@ method.
]]>
-
Explicit invocation of finalizer
- {1} explicitly invokes {2}
+ Explicit invocation of {2} in {1}
This method contains an explicit invocation of the finalize()
@@ -2380,18 +2866,42 @@ method.
If a connected set of objects beings finalizable, then the VM will invoke the
finalize method on all the finalizable object, possibly at the same time in different threads.
Thus, it is a particularly bad idea, in the finalize method for a class X, invoke finalize
-on objects referenced by X, because they may already be getting finalized in a separate thread.
+on objects referenced by X, because they may already be getting finalized in a separate thread.
]]>
+
+ Equals checks for incompatible operand
+ {1} checks for operand being a {2.givenClass}
+
+ This equals method is checking to see if the argument is some incompatible type
+(i.e., a class that is neither a supertype nor subtype of the class that defines
+the equals method). For example, the Foo class might have an equals method
+that looks like:
+
+
+public boolean equals(Object o) {
+ if (o instanceof Foo)
+ return name.equals(((Foo)o).name);
+ else if (o instanceof String)
+ return name.equals(o);
+ else return false;
+
+
This is considered bad practice, as it makes it very hard to implement an equals method that
+is symmetric and transitive. Without those properties, very unexpected behavoirs are possible.
+
+]]>
+
+ Covariant equals() method defined for enum
- enum {0} defines equals({0.givenClass})
+ Enum {0} defines equals({0.givenClass})
This class defines an enumeration, and equality on enumerations are defined
-using object identity. Definine a covariant equals method for an enumeration
+using object identity. Defining a covariant equals method for an enumeration
value is exceptionally bad practice, since it would likely result
in having two different enumeration values that compare as equals using
the covariant enum method, and as not equal when compared normally.
@@ -2433,7 +2943,7 @@ Don't do it.
This class defines an equals()
method, that doesn't override the normal equals(Object) method
- defined in the base java.lang.Object class. Instead, it
+ defined in the base java.lang.Object class. Instead, it
inherits an equals(Object) method from a superclass.
The class should probably define a boolean equals(Object) method.
@@ -2442,7 +2952,7 @@ Don't do it.
Class doesn't override equals in superclass
- {0} doesn't override {1.givenClass}
+ {0} doesn't override {2.givenClass}
This class extends a class that defines an equals method and adds fields, but doesn't
@@ -2475,47 +2985,110 @@ invoking super.equals(o).
This class defines an equals method that overrides an equals method in a superclass. Both equals methods
methods use instanceof in the determination of whether two objects are equal. This is fraught with peril,
-since it is important that the equals method is symetrical (in other words, a.equals(b) == b.equals(a)).
+since it is important that the equals method is symmetrical (in other words, a.equals(b) == b.equals(a)).
If B is a subtype of A, and A's equals method checks that the argument is an instanceof A, and B's equals method
checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these
methods is not symmetric.
+
+]]>
+
+
+
+ equals method fails for subtypes
+ {1} fails for subtypes
+
+ This class has an equals method that will be broken if it is inherited by subclasses.
+It compares a class literal with the class of the argument (e.g., in class Foo
+it might check if Foo.class == o.getClass()).
+It is better to check if this.getClass() == o.getClass().
+
+]]>
+
+
+
+ Unusual equals method
+ {1} is unusual
+
+ This class doesn't do any of the patterns we recognize for checking that the type of the argument
+is compatible with the type of the this object. There might not be anything wrong with
+this code, but it is worth reviewing.
+
+]]>
+
+
+
+ equals method compares class names rather than class objects
+ {1} compares class names rather than class objects
+
+ This method checks to see if two objects are the same class by checking to see if the names
+of their classes are equal. You can have different classes with the same name if they are loaded by
+different class loaders. Just check to see if the class objects are the same.
+
+]]>
+
+
+
+ equals method always returns true
+ {1} always returns true
+
+ This class defines an equals method that always returns true. This is imaginative, but not very smart.
+Plus, it means that the equals method is not symmetric.
+
+]]>
+
+
+
+ equals method always returns false
+ {1} always returns false
+
+ This class defines an equals method that always returns false. This means that an object is not equal to itself, and it is impossible to create useful Maps or Sets of this class. More fundamentally, it means
+that equals is not reflexive, one of the requirements of the equals method.
+
The likely intended semantics are object identity: that an object is equal to itself. This is the behavior inherited from class Object. If you need to override an equals inherited from a different
+superclass, you can use use:
If you don't think instances of this class will ever be inserted into a HashMap/HashTable,
the recommended hashCode implementation to use is:
-
public int hashCode() {
+
public int hashCode() {
assert false : "hashCode not designed";
- return 42; // any arbitrary constant will do
- }
+ return 42; // any arbitrary constant will do
+ }
]]>
-
-
-
Class defines compareTo(...) and uses Object.equals(){0} defines {1.givenClass} and uses Object.equals()
@@ -2600,26 +3206,22 @@ the recommended hashCode implementation to use is:
This class defines a compareTo(...) method but inherits its
equals() method from java.lang.Object.
- Generally, the value of compareTo should return zero if and only if
- equals returns true. If this is violated, weird and unpredictable
- failures will occur in classes such as PriorityQueue.
- In Java 5 the PriorityQueue.remove method uses the compareTo method,
- while in Java 6 it uses the equals method.
+ Generally, the value of compareTo should return zero if and only if
+ equals returns true. If this is violated, weird and unpredictable
+ failures will occur in classes such as PriorityQueue.
+ In Java 5 the PriorityQueue.remove method uses the compareTo method,
+ while in Java 6 it uses the equals method.
From the JavaDoc for the compareTo method in the Comparable interface:
-It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)).
-Generally speaking, any class that implements the Comparable interface and violates this condition
-should clearly indicate this fact. The recommended language
+It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)).
+Generally speaking, any class that implements the Comparable interface and violates this condition
+should clearly indicate this fact. The recommended language
is "Note: this class has a natural ordering that is inconsistent with equals."
-
+
]]>
-
-
-
-
Class defines hashCode() but not equals(){0} defines hashCode but not equals
@@ -2631,7 +3233,6 @@ is "Note: this class has a natural ordering that is inconsistent with equals."
]]>
-
Class defines equals() and uses Object.hashCode(){0} defines equals and uses Object.hashCode()
@@ -2648,7 +3249,7 @@ is "Note: this class has a natural ordering that is inconsistent with equals."
the recommended hashCode implementation to use is:
public int hashCode() {
assert false : "hashCode not designed";
- return 42; // any arbitrary constant will do
+ return 42; // any arbitrary constant will do
}
]]>
@@ -2695,7 +3296,6 @@ the recommended hashCode implementation to use is:
]]>
-
Comparison of String objects using == or !=Comparison of String objects using == or != in {1}
@@ -2716,14 +3316,13 @@ using the equals(Object) method instead.
This code compares a java.lang.String parameter for reference
-equality using the == or != operators. Requiring callers to
+equality using the == or != operators. Requiring callers to
pass only String constants or interned strings to a method is unnecessarily
fragile, and rarely leads to measurable performance gains. Consider
using the equals(Object) method instead.
]]>
-
Abstract class defines covariant compareTo() methodAbstract {0} defines compareTo({0.givenClass}) method
@@ -2736,19 +3335,30 @@ using the equals(Object) method instead.
]]>
-
-
Field not guarded against concurrent access{1.givenClass} not guarded against concurrent access; locked {2}% of time
This field is annotated with net.jcip.annotations.GuardedBy,
-but can be accessed in a way that seems to violate the annotation.
+
This field is annotated with net.jcip.annotations.GuardedBy or javax.annotation.concurrent.GuardedBy,
+but can be accessed in a way that seems to violate those annotations.
]]>
-
-
+
+
+ Mutable servlet field
+ {1} is a mutable servlet field
+
+A web server generally only creates one instance of servlet or jsp class (i.e., treats
+the class as a Singleton),
+and will
+have multiple threads invoke methods on that instance to service multiple
+simultaneous requests.
+Thus, having a mutable instance field generally creates race conditions.
+]]>
+
+ Inconsistent synchronizationInconsistent synchronization of {1}; locked {2}% of time
@@ -2758,12 +3368,13 @@ but can be accessed in a way that seems to violate the annotation.
to synchronization. This bug report indicates that the bug pattern detector
judged that
-
+
The class contains a mix of locked and unlocked accesses,
+
The class is not annotated as javax.annotation.concurrent.NotThreadSafe,
At least one locked access was performed by one of the class's own methods, and
The number of unsynchronized field accesses (reads and writes) was no more than
one third of all accesses, with writes being weighed twice as high as reads
-
+
A typical bug matching this bug pattern is forgetting to synchronize
one of the methods in a class that is intended to be thread-safe.
@@ -2778,9 +3389,6 @@ but can be accessed in a way that seems to violate the annotation.
distinguishing locked vs. unlocked accesses, the code in question may still
be correct.
-
This description refers to the "IS2" version of the pattern detector,
- which has more accurate ways of detecting locked vs. unlocked accesses
- than the older "IS" detector.
]]>
@@ -2804,7 +3412,7 @@ but can be accessed in a way that seems to violate the annotation.
Public static method may expose internal representation by returning array
- public static {1} may expose internal representation by returning {2.givenClass}
+ Public static {1} may expose internal representation by returning {2.givenClass}
A public static method returns a reference to
@@ -2890,7 +3498,7 @@ but can be accessed in a way that seems to violate the annotation.
This code seems to be using non-short-circuit logic (e.g., &
or |)
-rather than short-circuit logic (&& or ||). In addition,
+rather than short-circuit logic (&& or ||). In addition,
it seem possible that, depending on the value of the left hand side, you might not
want to evaluate the right hand side (because it would have side effects, could cause an exception
or could be expensive.
@@ -2928,12 +3536,8 @@ Language Specification for details
]]>
-
-
-
-
-
-
+
+
Wait with two locks heldwait() with two locks held in {1}
@@ -2950,7 +3554,8 @@ This not necessarily a bug, but is worth examining
]]>
-
+
+
Notify with two locks heldnotify() or notifyAll*() with two locks held in {1}
@@ -2966,7 +3571,6 @@ This not necessarily a bug, but is worth examining
]]>
-
Unconditional waitUnconditional wait in {1}
@@ -2974,8 +3578,8 @@ This not necessarily a bug, but is worth examining
This method contains a call to java.lang.Object.wait() which
is not guarded by conditional control flow. The code should
- verify that condition it intends to wait for is not already satisfied
- before calling wait; any previous notifications will be ignored.
+ verify that condition it intends to wait for is not already satisfied
+ before calling wait; any previous notifications will be ignored.
]]>
@@ -2988,6 +3592,39 @@ This not necessarily a bug, but is worth examining
This constructor reads a field which has not yet been assigned a value.
This is often caused when the programmer mistakenly uses the field instead
of one of the constructor's parameters.
+]]>
+
+
+
+ Uninitialized read of field method called from constructor of superclass
+ {2.name} isn't initialized in {1} when invoked from constructor for superclass
+
+ This method is invoked in the constructor of of the superclass. At this point,
+ the fields of the class have not yet initialized.
+
To make this more concrete, consider the following classes:
When a B is constructed,
+the constructor for the A class is invoked
+before the constructor for B sets value.
+Thus, when the constructor for A invokes getValue,
+an uninitialized value is read for value
+
]]>
@@ -3004,7 +3641,6 @@ This not necessarily a bug, but is worth examining
]]>
-
Initialization circularityInitialization circularity between {0} and {1}
@@ -3016,7 +3652,6 @@ This not necessarily a bug, but is worth examining
]]>
-
Superclass uses subclass during initializationInitialization of {0} accesses class {2}, which isn't initialized yet
@@ -3028,23 +3663,20 @@ For example, in the following code, foo will be null.
public class CircularClassInitialization {
- static class InnerClassSingleton extends CircularClassInitialization {
- static InnerClassSingleton singleton = new InnerClassSingleton();
- }
-
- static CircularClassInitialization foo = InnerClassSingleton.singleton;
+ static class InnerClassSingleton extends CircularClassInitialization {
+ static InnerClassSingleton singleton = new InnerClassSingleton();
+ }
+
+ static CircularClassInitialization foo = InnerClassSingleton.singleton;
}
]]>
-
-
-
- Iterator next() method can't throw NoSuchElement exception
- {1} can't throw NoSuchElement exception
+ Iterator next() method can't throw NoSuchElementException
+ {1} can't throw NoSuchElementException
This class implements the java.util.Iterator interface.
@@ -3055,102 +3687,98 @@ public class CircularClassInitialization {
]]>
-
- Synchronization on interned String could lead to deadlock
- Synchronization on interned String could deadlock in {1}
+ Synchronization on interned String
+ Synchronization on interned String in {1}
The code synchronizes on interned String.
+
]]>
- Synchronization on Boolean could lead to deadlock
- Synchronization on Boolean could deadlock in {1}
+ Synchronization on Boolean
+ Synchronization on Boolean in {1}
The code synchronizes on a boxed primitive constant, such as an Boolean.
+
The code synchronizes on a boxed primitive constant, such as an Boolean.
Since there normally exist only two Boolean objects, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness
and possible deadlock
]]>
-
- Synchronization boxed primative values
+ Synchronization on boxed primitive valuesSynchronization on {2} in {1}
The code synchronizes on an apparently unshared boxed primitive,
-such as an Integer.
+
The code synchronizes on an apparently unshared boxed primitive,
+such as an Integer.
private static final Integer fileLock = new Integer(1);
...
- synchronized(fileLock) {
+ synchronized(fileLock) {
.. do something ..
}
...
-
-
It would be much better, in this code, to redeclare fileLock as
+
It would be much better, in this code, to redeclare fileLock as
private static final Object fileLock = new Object();
-The existing code might be OK, but it is confusing and a
-future refactoing, such as the "Remove Boxing" refactoring in IntelliJ,
-might replace this with the use of an intern'd Integer object shared
+
+The existing code might be OK, but it is confusing and a
+future refactoring, such as the "Remove Boxing" refactoring in IntelliJ,
+might replace this with the use of an interned Integer object shared
throughout the JVM, leading to very confusing behavior and potential deadlock.
]]>
-
- Synchronization on boxed primative could lead to deadlock
- Synchronization on {2} could deadlock in {1}
+ Synchronization on boxed primitive
+ Synchronization on {2} in {1}
The code synchronizes on a boxed primitive constant, such as an Integer.
+
The code synchronizes on a boxed primitive constant, such as an Integer.
Since Integer objects can be cached and shared,
this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness
and possible deadlock
]]>
-
Empty synchronized blockEmpty synchronized block in {1}
@@ -3168,7 +3796,6 @@ than less contrived solutions.
]]>
-
Inconsistent synchronizationInconsistent synchronization of {1}; locked {2}% of the time
@@ -3178,12 +3805,12 @@ than less contrived solutions.
to synchronization. This bug report indicates that the bug pattern detector
judged that
-
+
The class contains a mix of locked and unlocked accesses,
At least one locked access was performed by one of the class's own methods, and
The number of unsynchronized field accesses (reads and writes) was no more than
one third of all accesses, with writes being weighed twice as high as reads
-
+
A typical bug matching this bug pattern is forgetting to synchronize
one of the methods in a class that is intended to be thread-safe.
@@ -3196,7 +3823,6 @@ than less contrived solutions.
]]>
-
Synchronization on field in futile attempt to guard that fieldSynchronization on {2.givenClass} in futile attempt to guard it
@@ -3204,12 +3830,11 @@ than less contrived solutions.
This method synchronizes on a field in what appears to be an attempt
to guard against simultaneous updates to that field. But guarding a field
-gets a lock on the referenced object, not on the field. This may not
-provide the mutual exclusion you need, and other threads might
+gets a lock on the referenced object, not on the field. This may not
+provide the mutual exclusion you need, and other threads might
be obtaining locks on the referenced objects (for other purposes). An example
-of this pattern would be:
-
-
+of this pattern would be:
+
private Long myNtfSeqNbrCounter = new Long(0);
private Long getNotificationSequenceNumber() {
Long result = null;
@@ -3220,9 +3845,6 @@ private Long getNotificationSequenceNumber() {
return result;
}
-
-
-
]]>
@@ -3238,8 +3860,6 @@ threads may be synchronizing on different objects.
]]>
-
-
Field should be moved out of an interface and made package protected{1} should be moved out of an interface and made package protected
@@ -3270,6 +3890,22 @@ defined in an interface references a mutable
The field could be made package protected and/or made final
to avoid
this vulnerability.
+]]>
+
+
+
+ Field isn't final but should be refactored to be so
+ {1} isn't final but should be refactored to be so
+
+
+This static field public but not final, and
+could be changed by malicious code or
+by accident from another package.
+The field could be made final to avoid
+this vulnerability. However, the static initializer contains more than one write
+to the field, so doing so will require some refactoring.
+
]]>
@@ -3279,7 +3915,8 @@ defined in an interface references a mutable
- A mutable static field could be changed by malicious code or
+This static field public but not final, and
+could be changed by malicious code or
by accident from another package.
The field could be made final to avoid
this vulnerability.
@@ -3307,6 +3944,31 @@ defined in an interface references a mutable
and can be accessed by malicious code or
by accident from another package.
This code can freely modify the contents of the Hashtable.
+]]>
+
+
+
+ Field is a mutable collection
+ {1} is a mutable collection
+
+A mutable collection instance is assigned to a final static field,
+ thus can be changed by malicious code or by accident from another package.
+ Consider wrapping this field into Collections.unmodifiableSet/List/Map/etc.
+ to avoid this vulnerability.
+]]>
+
+
+
+ Field is a mutable collection which should be package protected
+ {1} is a mutable collection which should be package protected
+
+A mutable collection instance is assigned to a final static field,
+ thus can be changed by malicious code or by accident from another package.
+ The field could be made package protected to avoid this vulnerability.
+ Alternatively you may wrap this field into Collections.unmodifiableSet/List/Map/etc.
+ to avoid this vulnerability.
]]>
@@ -3335,19 +3997,50 @@ defined in an interface references a mutable
]]>
-
+
+ Enum field is public and mutable
+ {1} field is public and mutable
+
+A mutable public field is defined inside a public enum, thus can be changed by malicious code or by accident from another package.
+ Though mutable enum fields may be used for lazy initialization, it's a bad practice to expose them to the outer world.
+ Consider declaring this field final and/or package-private.
+]]>
+
+
+
+ Public enum method unconditionally sets its field
+ {1} unconditionally sets the field {2.name}
+
+This public method declared in public enum unconditionally sets enum field, thus this field can be changed by malicious code
+ or by accident from another package. Though mutable enum fields may be used for lazy initialization, it's a bad practice to expose them to the outer world.
+ Consider removing this method or declaring it package-private.
+]]>
+
+
- Ambiguous invocation of either an inherited or outer method
- Ambiguous invocation of either an outer or inherited method {2} in {1}
+ Potentially ambiguous invocation of either an inherited or outer method
+ Potentially ambiguous invocation of either an outer or inherited method {2} in {1}
An inner class is invoking a method that could be resolved to either a inherited method or a method defined in an outer class. By the Java semantics,
+
+An inner class is invoking a method that could be resolved to either a inherited method or a method defined in an outer class.
+For example, you invoke foo(17), which is defined in both a superclass and in an outer method.
+By the Java semantics,
it will be resolved to invoke the inherited method, but this may not be want
-you intend. If you really intend to invoke the inherited method,
+you intend.
+
+
If you really intend to invoke the inherited method,
invoke it by invoking the method on super (e.g., invoke super.foo(17)), and
thus it will be clear to other readers of your code and to FindBugs
that you want to invoke the inherited method, not the method in the outer class.
+
If you call this.foo(17), then the inherited method will be invoked. However, since FindBugs only looks at
+classfiles, it
+can't tell the difference between an invocation of this.foo(17) and foo(17), it will still
+complain about a potential ambiguous invocation.
+
]]>
@@ -3357,10 +4050,10 @@ that you want to invoke the inherited method, not the method in the outer class.
This class has a simple name that is identical to that of its superclass, except
-that its superclass is in a different package (e.g., alpha.Foo extends beta.Foo).
+that its superclass is in a different package (e.g., alpha.Foo extends beta.Foo).
This can be exceptionally confusing, create lots of situations in which you have to look at import statements
to resolve references and creates many
-opportunities to accidently define methods that do not override methods in their superclasses.
+opportunities to accidentally define methods that do not override methods in their superclasses.
]]>
@@ -3370,16 +4063,15 @@ opportunities to accidently define methods that do not override methods in their
The class name {0} shadows the simple name of implemented interface {1}
This class/interface has a simple name that is identical to that of an implemented/extended interface, except
-that the interface is in a different package (e.g., alpha.Foo extends beta.Foo).
+
This class/interface has a simple name that is identical to that of an implemented/extended interface, except
+that the interface is in a different package (e.g., alpha.Foo extends beta.Foo).
This can be exceptionally confusing, create lots of situations in which you have to look at import statements
to resolve references and creates many
-opportunities to accidently define methods that do not override methods in their superclasses.
+opportunities to accidentally define methods that do not override methods in their superclasses.
]]>
-
Class names should start with an upper case letterThe class name {0} doesn't start with an upper case letter
@@ -3390,7 +4082,6 @@ opportunities to accidently define methods that do not override methods in their
]]>
-
Method names should start with a lower case letterThe method name {1} doesn't start with a lower case letter
@@ -3402,7 +4093,6 @@ Methods should be verbs, in mixed case with the first letter lowercase, with the
]]>
-
Field names should start with a lower case letterThe field name {1} doesn't start with a lower case letter
@@ -3414,13 +4104,12 @@ Names of fields that are not final should be in mixed case with a lowercase firs
]]>
-
Very confusing method namesVERY confusing to have methods {1} and {3}
The referenced methods have names that differ only by capitalization.
+
The referenced methods have names that differ only by capitalization.
This is very confusing because if the capitalization were
identical then one of the methods would override the other.
@@ -3428,14 +4117,14 @@ identical then one of the methods would override the other.
- Very confusing method names
+ Very confusing method names (but perhaps intentional)VERY confusing (but perhaps intentional) to have methods {1} and {3}
The referenced methods have names that differ only by capitalization.
+
The referenced methods have names that differ only by capitalization.
This is very confusing because if the capitalization were
identical then one of the methods would override the other. From the existence of other methods, it
-seems that the existence of both of these methods is intentional, but is sure is confusing.
+seems that the existence of both of these methods is intentional, but is sure is confusing.
You should try hard to eliminate one of them, unless you are forced to have both due to frozen APIs.
]]>
@@ -3464,7 +4153,7 @@ public class B extends A {
The f(Foo) method defined in class B doesn't
-override the
+override the
f(Foo) method defined in class A, because the argument
types are Foo's from different packages.
@@ -3495,7 +4184,7 @@ public class B extends A {
The f(Foo) method defined in class B doesn't
-override the
+override the
f(Foo) method defined in class A, because the argument
types are Foo's from different packages.
@@ -3507,8 +4196,6 @@ removing or deprecating the method with the similar but not identical signature.
]]>
-
-
Confusing method namesConfusing to have methods {1} and {3}
@@ -3520,13 +4207,13 @@ removing or deprecating the method with the similar but not identical signature.
Apparent method/constructor confusion
- Method {1} was probably intended to be a constructor
+ {1} was probably intended to be a constructor
This regular method has the same name as the class it is defined in. It is likely that this was intended to be a constructor.
If it was intended to be a constructor, remove the declaration of a void return value.
- If you had accidently defined this method, realized the mistake, defined a proper constructor
- but can't get rid of this method due to backwards compatibility, deprecate the method.
+ If you had accidentally defined this method, realized the mistake, defined a proper constructor
+ but can't get rid of this method due to backwards compatibility, deprecate the method.
]]>
@@ -3553,10 +4240,9 @@ removing or deprecating the method with the similar but not identical signature.
]]>
-
- Class defines equal(); should it be equals()?
- Class {0} defines equal(); should it be equals()?
+ Class defines equal(Object); should it be equals(Object)?
+ Class {0} defines equal(Object); should it be equals(Object)?
This class defines a method equal(Object). This method does
@@ -3565,7 +4251,6 @@ which is probably what was intended.
]]>
-
Class is not derived from an Exception, even though it is named as suchClass {0} is not derived from an Exception, even though it is named as such
@@ -3576,7 +4261,6 @@ be confusing to users of this class.
]]>
-
Method ignores results of InputStream.read(){1} ignores result of {2}
@@ -3606,17 +4290,38 @@ be confusing to users of this class.
causing the program to fail only sporadically. With Buffered streams, however,
skip() will only skip data in the buffer, and will routinely fail to skip the
requested number of bytes.
+]]>
+
+
+
+ The readResolve method must not be declared as a static method.
+ {1} should be declared as an instance method rather than a static method
+
+ In order for the readResolve method to be recognized by the serialization
+mechanism, it must not be declared as a static method.
+
+]]>
+
+
+
+ Private readResolve method not inherited by subclasses
+ Private readResolve method in {0} not inherited by subclasses.
+
+ This class defines a private readResolve method. Since it is private, it won't be inherited by subclasses.
+This might be intentional and OK, but should be reviewed to ensure it is what is intended.
+
]]>
- The readResolve method must be declared with a return type
-of Object.
+ The readResolve method must be declared with a return type of Object. The method {1} must be declared with a return type of Object rather than {1.returnType}
In order for the readResolve method to be recognized by the serialization
-mechanism.
+mechanism, it must be declared to have a return type of Object.
]]>
@@ -3627,38 +4332,35 @@ mechanism.
The field is marked as transient, but the class isn't Serializable, so marking it as transient
-has absolutely no effect.
+has absolutely no effect.
This may be leftover marking from a previous version of the code in which the class was transient, or
it may indicate a misunderstanding of how serialization works.
]]>
-
Transient field that isn't set by deserialization. The field {1} is transient but isn't set by deserialization
This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any
+
This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any
deserialized instance of the class.
]]>
-
Method must be private in order for serialization to workThe method {1.givenClass} must be private to be invoked in serialization/deserialization of {0}
This class implements the Serializable interface, and defines a method
- for custom serialization/deserialization. But since that method isn't declared private,
+ for custom serialization/deserialization. But since that method isn't declared private,
it will be silently ignored by the serialization/deserialization API.
]]>
-
Class is Externalizable but doesn't define a void constructor{0} is Externalizable but doesn't define a void constructor
@@ -3674,7 +4376,7 @@ deserialized instance of the class.
Class is Serializable but its superclass doesn't define a void constructor
- {0} is Serializable but its superclass doesn't define an accessible void constructor
+ {0} is Serializable but its superclass doesn't define an accessible void constructor
This class implements the Serializable interface
@@ -3686,7 +4388,6 @@ deserialized instance of the class.
]]>
-
Class is Serializable, but doesn't define serialVersionUID{0} is Serializable; consider declaring a serialVersionUID
@@ -3723,29 +4424,52 @@ is generally easy and good defensive programming.
]]>
-
- Switch statement found where one case falls through to the next case
- Switch statement found in {1} where one case falls through to the next case
+ Switch statement found where one case falls through to the next case
+ Switch statement found in {1} where one case falls through to the next case
This method contains a switch statement where one case branch will fall through to the next case.
Usually you need to end this case with a break or return.
+]]>
+
+
+
+ Switch statement found where default case is missing
+ Switch statement found in {1} where default case is missing
+
+ This method contains a switch statement where default case is missing.
+ Usually you need to provide a default case.
+
Because the analysis only looks at the generated bytecode, this warning can be incorrect triggered if
+the default case is at the end of the switch statement and the switch statement doesn't contain break statements for other
+cases.
]]>
- Dead store due to switch statement fall through
- Value of {2.givenClass} from previous case is overwritten here due to switch statement fall through
+ Dead store due to switch statement fall through
+ Value of {2.givenClass} from previous case is overwritten here due to switch statement fall through
A value stored in the previous switch case is overwritten here due to a switch fall through. It is likely that
- you forgot to put a break or return at the end of the previous case.
+ you forgot to put a break or return at the end of the previous case.
+
+]]>
+
+
+
+ Dead store due to switch statement fall through to throw
+ Value of {2.givenClass} from previous case is lost here due to switch statement fall through to throw
+
+ A value stored in the previous switch case is ignored here due to a switch fall through to a place where
+ an exception is thrown. It is likely that
+ you forgot to put a break or return at the end of the previous case.
]]>
-
Class's writeObject() method is synchronized but nothing else is{0}'s writeObject method is synchronized but nothing else is
@@ -3770,7 +4494,6 @@ is generally easy and good defensive programming.
]]>
-
serialVersionUID isn't static{1} isn't static
@@ -3783,7 +4506,6 @@ is generally easy and good defensive programming.
]]>
-
serialVersionUID isn't final{1} isn't final
@@ -3796,8 +4518,6 @@ is generally easy and good defensive programming.
]]>
-
-
serialVersionUID isn't long{1} isn't long
@@ -3810,7 +4530,6 @@ is generally easy and good defensive programming.
]]>
-
Non-transient non-serializable instance field in serializable classClass {0} defines non-transient non-serializable instance field {1.name}
@@ -3825,7 +4544,6 @@ object is stored in this field.
]]>
-
Non-serializable class has a serializable inner class{0} is serializable but also an inner class of a non-serializable class
@@ -3835,7 +4553,7 @@ object is stored in this field.
Thus, attempts to serialize it will also attempt to associate instance of the outer
class with which it is associated, leading to a runtime error.
-
If possible, making the inner class a static inner class should solve the
+
If possible, making the inner class a static inner class should solve the
problem. Making the outer class serializable might also work, but that would
mean serializing an instance of the inner class would always also serialize the instance
of the outer class, which it often not what you really want.
@@ -3850,12 +4568,11 @@ of the outer class, which it often not what you really want.
This Serializable class is an inner class. Any attempt to serialize
it will also serialize the associated outer instance. The outer instance is serializable,
so this won't fail, but it might serialize a lot more data than intended.
-If possible, making the inner class a static inner class (also known as a nested class) should solve the
-problem.
+If possible, making the inner class a static inner class (also known as a nested class) should solve the
+problem.
]]>
-
Non-serializable value stored into instance field of a serializable class{2} stored into non-transient field {1.givenClass}
@@ -3866,7 +4583,6 @@ of a serializable class.
]]>
-
Constructor invokes Thread.start(){1} invokes {2}
@@ -3907,7 +4623,30 @@ of a serializable class.
]]>
-
+
+ Unused public or protected field
+ Unused public or protected field: {1}
+
+ This field is never used.
+The field is public or protected, so perhaps
+ it is intended to be used with classes not seen as part of the analysis. If not,
+consider removing it from the class.
+]]>
+
+
+
+ Unread public/protected field
+ Unread public/protected field: {1}
+
+ This field is never read.
+The field is public or protected, so perhaps
+ it is intended to be used with classes not seen as part of the analysis. If not,
+consider removing it from the class.
+]]>
+
+ Complicated, subtle or wrong increment in for-loop Complicated, subtle or wrong increment in for-loop {1}
@@ -3928,6 +4667,16 @@ of a serializable class.
All writes to this field are of the constant value null, and thus
all reads of the field will return null.
Check for errors, or remove it if it is useless.
+]]>
+
+
+
+ Unwritten public or protected field
+ Unwritten public or protected field: {1}
+
+ No writes were seen to this public/protected field. All reads of it will return the default
+value. Check for errors (should it have been initialized?), or remove it if it is useless.
]]>
@@ -3941,8 +4690,6 @@ value. Check for errors (should it have been initialized?), or remove it if it i
]]>
-
-
Write to static field from instance methodWrite to static field {2} from instance method {1}
@@ -3955,7 +4702,6 @@ and generally bad practice.
]]>
-
Load of known null valueLoad of known null value in {1}
@@ -3964,12 +4710,22 @@ and generally bad practice.
The variable referenced at this point is known to be null due to an earlier
check against null. Although this is valid, it might be a mistake (perhaps you
intended to refer to a different variable, or perhaps the earlier check to see if the
-variable is null should have been a check to see if it was nonnull).
+variable is null should have been a check to see if it was non-null).
+
+]]>
+
+
+
+ Dereference of the result of readLine() without nullcheck
+ Dereference of the result of readLine() without nullcheck in {1}
+
+ The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text
+to read, readLine() will return null and dereferencing that will generate a null pointer exception.
]]>
-
Immediate dereference of the result of readLine()Immediate dereference of the result of readLine() in {1}
@@ -3981,19 +4737,47 @@ to read, readLine() will return null and dereferencing that will generate a null
]]>
-
Read of unwritten fieldRead of unwritten field {2.name} in {1}
The program is dereferencing a field that does not seem to ever have a non-null value written to it.
-Dereferencing this value will generate a null pointer exception.
+Unless the field is initialized via some mechanism not seen by the analysis,
+dereferencing this value will generate a null pointer exception.
+
+]]>
+
+
+
+ Read of unwritten public or protected field
+ Read of unwritten public or protected field {2.name} in {1}
+
+ The program is dereferencing a public or protected
+field that does not seem to ever have a non-null value written to it.
+Unless the field is initialized via some mechanism not seen by the analysis,
+dereferencing this value will generate a null pointer exception.
+
+]]>
+
+
+
+ Deadly embrace of non-static inner class and thread local
+ {0} needs to be _static_ to avoid a deadly embrace with {1}
+
+ This class is an inner class, but should probably be a static inner class.
+ As it is, there is a serious danger of a deadly embrace between the inner class
+ and the thread local in the outer class. Because the inner class isn't static,
+ it retains a reference to the outer class.
+ If the thread local contains a reference to an instance of the inner
+ class, the inner and outer instance will both be reachable
+ and not eligible for garbage collection.
]]>
-
Should be a static inner classShould {0} be a _static_ inner class?
@@ -4008,29 +4792,13 @@ Dereferencing this value will generate a null pointer exception.
]]>
-
-
-
-
- Read of field not initialized in constructor
- Read of field not initialized in constructor at {1}
-
- This is a read of a field is never initialized within any constructor, and is therefore could be null after
-the object is initialized. This might be a coding error, or else the class containing the field
-is written in a way that depends upon methods being called in some specific order (a little bit dodgy,
-but not necessarily wrong).
-
-]]>
-
-
- Field not initialized in constructor
- {1.givenClass} not initialized in constructor
+ Field not initialized in constructor but dereferenced without null check
+ {1.givenClass} not initialized in constructor and dereferenced in {2}
This field is never initialized within any constructor, and is therefore could be null after
-the object is constructed.
+the object is constructed. Elsewhere, it is loaded and dereferenced without a null check.
This could be a either an error or a questionable design, since
it means a null pointer exception will be generated if that field is dereferenced
before being initialized.
@@ -4038,81 +4806,172 @@ before being initialized.
]]>
-
Could be refactored into a named static inner classThe class {0} could be refactored into a named _static_ inner class
This class is an inner class, but does not use its embedded reference
- to the object which created it. This reference makes the instances
- of the class larger, and may keep the reference to the creator object
- alive longer than necessary. If possible, the class should be
- made into a static inner class. Since anonymous inner
-classes cannot be marked as static, doing this will require refactoring
-the inner class so that it is a named inner class.
+
This class is an inner class, but does not use its embedded reference
+ to the object which created it. This reference makes the instances
+ of the class larger, and may keep the reference to the creator object
+ alive longer than necessary. If possible, the class should be
+ made into a static inner class. Since anonymous inner
+classes cannot be marked as static, doing this will require refactoring
+the inner class so that it is a named inner class.
+]]>
+
+
+
+ Could be refactored into a static inner class
+ The class {0} could be refactored into a _static_ inner class
+
+ This class is an inner class, but does not use its embedded reference
+ to the object which created it except during construction of the
+inner object. This reference makes the instances
+ of the class larger, and may keep the reference to the creator object
+ alive longer than necessary. If possible, the class should be
+ made into a static inner class. Since the reference to the
+ outer object is required during construction of the inner instance,
+ the inner class will need to be refactored so as to
+ pass a reference to the outer instance to the constructor
+ for the inner class.
+]]>
+
+
+
+ Wait not in loop
+ Wait not in loop in {1}
+
+ This method contains a call to java.lang.Object.wait()
+ which is not in a loop. If the monitor is used for multiple conditions,
+ the condition the caller intended to wait for might not be the one
+ that actually occurred.
+]]>
+
+
+
+ Condition.await() not in loop
+ Condition.await() not in loop in {1}
+
+ This method contains a call to java.util.concurrent.await()
+ (or variants)
+ which is not in a loop. If the object is used for multiple conditions,
+ the condition the caller intended to wait for might not be the one
+ that actually occurred.
+]]>
+
+
+
+ Using notify() rather than notifyAll()
+ Using notify rather than notifyAll in {1}
+
+ This method calls notify() rather than notifyAll().
+ Java monitors are often used for multiple conditions. Calling notify()
+ only wakes up one thread, meaning that the thread woken up might not be the
+ one waiting for the condition that the caller just satisfied.
+]]>
+
+
+
+ Useless non-empty void method
+ Method {1} seems to be useless
+
+Our analysis shows that this non-empty void method does not actually perform any useful work.
+Please check it: probably there's a mistake in its code or its body can be fully removed.
+
+
We are trying to reduce the false positives as much as possible, but in some cases this warning might be wrong.
+Common false-positive cases include:
+
- The method is intended to trigger loading of some class which may have a side effect.
+
- The method is intended to implicitly throw some obscure exception.
+]]>
+
+
+
+ Condition has no effect
+ Useless condition: it's known that {2} at this point
+
+This condition always produces the same result as the value of the involved variable was narrowed before.
+Probably something else was meant or condition can be removed.
+]]>
+
+
+
+ Condition has no effect due to the variable type
+ Useless condition: it's always {2} because variable type is {3}
+
+This condition always produces the same result due to the type range of the involved variable.
+Probably something else was meant or condition can be removed.
+]]>
+
+
+
+ Useless object created
+ Useless object stored in variable {2} of method {1}
+
+Our analysis shows that this object is useless.
+It's created and modified, but its value never go outside of the method or produce any side-effect.
+Either there is a mistake and object was intended to be used or it can be removed.
+
This analysis rarely produces false-positives. Common false-positive cases include:
+
- This object used to implicitly throw some obscure exception.
+
- This object used as a stub to generalize the code.
+
- This object used to hold strong references to weak/soft-referenced objects.
+]]>
+
+
+
+ Useless object created on stack
+ Useless object created in method {1}
+
+This object is created just to perform some modifications which don't have any side-effect.
+Probably something else was meant or the object can be removed.
]]>
-
- Could be refactored into a static inner class
- The class {0} could be refactored into a _static_ inner class
+
+ Array index is out of bounds
+ Array index is out of bounds: {3}
This class is an inner class, but does not use its embedded reference
- to the object which created it except during construction of the
-inner object. This reference makes the instances
- of the class larger, and may keep the reference to the creator object
- alive longer than necessary. If possible, the class should be
- made into a static inner class. Since the reference to the
- outer object is required during construction of the inner instance,
- the inner class will need to be refactored so as to
- pass a reference to the outer instance to the constructor
- for the inner class.
+
Array operation is performed, but array index is out of bounds, which will result in ArrayIndexOutOfBoundsException at runtime.
]]>
-
-
- Wait not in loop
- Wait not in loop in {1}
+
+ Array offset is out of bounds
+ Array offset is out of bounds: {3}
This method contains a call to java.lang.Object.wait()
- which is not in a loop. If the monitor is used for multiple conditions,
- the condition the caller intended to wait for might not be the one
- that actually occurred.
+
Method is called with array parameter and offset parameter, but the offset is out of bounds. This will result in IndexOutOfBoundsException at runtime.
]]>
-
-
- Condition.await() not in loop
- Condition.await() not in loop in {1}
+
+ Array length is out of bounds
+ Array length is out of bounds: {3}
This method contains a call to java.util.concurrent.await()
- (or variants)
- which is not in a loop. If the object is used for multiple conditions,
- the condition the caller intended to wait for might not be the one
- that actually occurred.
+
Method is called with array parameter and length parameter, but the length is out of bounds. This will result in IndexOutOfBoundsException at runtime.
]]>
-
-
- Using notify() rather than notifyAll()
- Using notify rather than notifyAll in {1}
+
+ String index is out of bounds
+ String index is out of bounds when calling {5}: {3}
This method calls notify() rather than notifyAll().
- Java monitors are often used for multiple conditions. Calling notify()
- only wakes up one thread, meaning that the thread woken up might not be the
- one waiting for the condition that the caller just satisfied.
+
String method is called and specified string index is out of bounds. This will result in StringIndexOutOfBoundsException at runtime.
]]>
-
Method checks to see if result of String.indexOf is positive{1} checks to see if result of String.indexOf is positive
@@ -4125,10 +4984,9 @@ inner object. This reference makes the instances
]]>
-
- Method discards result of readLine after checking if it is nonnull
- {1} discards result of readLine after checking if it is nonnull
+ Method discards result of readLine after checking if it is non-null
+ {1} discards result of readLine after checking if it is non-null
The value returned by readLine is discarded after checking to see if the return
@@ -4138,10 +4996,51 @@ to use that non-null value. Calling readLine again will give you a different lin
+
+ Method ignores return value, is this OK?
+ Return value of {2.givenClass} ignored, is this OK in {1}
+
+This code calls a method and ignores the return value. The return value
+is the same type as the type the method is invoked on, and from our analysis it looks
+like the return value might be important (e.g., like ignoring the
+return value of String.toLowerCase()).
+
+
We are guessing that ignoring the return value might be a bad idea just from
+a simple analysis of the body of the method. You can use a @CheckReturnValue annotation
+to instruct FindBugs as to whether ignoring the return value of this method
+is important or acceptable.
+
+
Please investigate this closely to decide whether it is OK to ignore the return value.
+
+]]>
+
+
+
+
+ Return value of method without side effect is ignored
+ Return value of {2.givenClass} ignored, but method has no side effect
+
+This code calls a method and ignores the return value. However our analysis shows that
+the method (including its implementations in subclasses if any) does not produce any effect
+other than return value. Thus this call can be removed.
+
+
We are trying to reduce the false positives as much as possible, but in some cases this warning might be wrong.
+Common false-positive cases include:
+
- The method is designed to be overridden and produce a side effect in other projects which are out of the scope of the analysis.
+
- The method is called to trigger the class loading which may have a side effect.
+
- The method is called just to get some exception.
+
If you feel that our assumption is incorrect, you can use a @CheckReturnValue annotation
+to instruct FindBugs that ignoring the return value of this method is acceptable.
+
+]]>
+
+ Method ignores return value
- {1} ignores return value of {2}
+ Return value of {2.givenClass} ignored in {1}
The return value of this method should be checked. One common
@@ -4167,15 +5066,17 @@ dateString = dateString.trim();
]]>
+
+
Method ignores exceptional return value
- {1} ignores exceptional return value of {2}
+ Exceptional return value of {2} ignored in {1}
This method returns a value that is not checked. The return value should be checked
since it can indicate an unusual or unexpected function execution. For
example, the File.delete() method returns false
-if the file could not be successfully deleted (rather than
+if the file could not be successfully deleted (rather than
throwing an Exception).
If you don't check the result, you won't notice if the method invocation
signals unexpected behavior by returning an atypical return value.
@@ -4183,15 +5084,25 @@ signals unexpected behavior by returning an atypical return value.
]]>
-
-
+
+ Code checks for specific values returned by compareTo
+ Check to see if return value of {2.givenClass} is equal to {3}
+
+ This code invoked a compareTo or compare method, and checks to see if the return value is a specific value,
+such as 1 or -1. When invoking these methods, you should only check the sign of the result, not for any specific
+non-zero value. While many or most compareTo and compare methods only return -1, 0 or 1, some of them
+will return other values.
+]]>
+
+ Exception created and dropped rather than thrown
- {1} forgets to throw {2.givenClass}
+ {2.givenClass} not thrown in {1}
This code creates an exception (or error) object, but doesn't do anything with it. For example,
-something like
+something like
if (x < 0)
@@ -4208,38 +5119,6 @@ if (x < 0)
]]>
-
-
-
-
- Method ignores return value
- {1} ignores return value of {2}
-
- The return value of this method should be checked. One common
-cause of this warning is to invoke a method on an immutable object,
-thinking that it updates the object. For example, in the following code
-fragment,
-
the programmer seems to be thinking that the trim() method will update
-the String referenced by dateString. But since Strings are immutable, the trim()
-function returns a new String value, which is being ignored here. The code
-should be corrected to:
-]]>
-
-
-
Null pointer dereferenceNull pointer dereference of {2.givenClass} in {1}
@@ -4247,15 +5126,26 @@ dateString = dateString.trim();
A null pointer is dereferenced here. This will lead to a
NullPointerException when the code is executed.
+]]>
+
+
+
+ close() invoked on a value that is always null
+ Can't close {2.givenClass} since it is always null in {1}
+
+ close() is being invoked on a value that is always null. If this statement is executed,
+a null pointer exception will occur. But the big risk here you never close
+something that should be closed.
]]>
- Store of null value into field annotated NonNull
- Store of null value into field {2.givenClass} annotated NonNull at {1}
+ Store of null value into field annotated @Nonnull
+ Store of null value into field {2.givenClass} annotated @Nonnull in {1}
A value that could be null is stored into a field that has been annotated as NonNull.
+
A value that could be null is stored into a field that has been annotated as @Nonnull.
]]>
@@ -4274,7 +5164,18 @@ be an exception path, since the default case is often infeasible.
]]>
-
+
+ Parameter must be non-null but is marked as nullable
+ {2} must be non-null but is marked as nullable
+
+ This parameter is always used in a way that requires it to be non-null,
+but the parameter is explicitly annotated as being Nullable. Either the use
+of the parameter or the annotation is wrong.
+
+]]>
+
+ Possible null pointer dereferencePossible null pointer dereference of {2.givenClass} in {1}
@@ -4289,10 +5190,9 @@ the null pointer exception can't ever be executed; deciding that is beyond the a
]]>
-
- Possible null pointer dereference on path that might be infeasible
- Possible null pointer dereference of {2.givenClass} on path that might be infeasible in {1}
+ Possible null pointer dereference on branch that might be infeasible
+ Possible null pointer dereference of {2.givenClass} on branch that might be infeasible in {1}
There is a branch of statement that, if executed, guarantees that
@@ -4300,12 +5200,12 @@ a null value will be dereferenced, which
would generate a NullPointerException when the code is executed.
Of course, the problem might be that the branch or statement is infeasible and that
the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.
-Due to the fact that this value had been previously tested for nullness, this is a definite possiblity.
+Due to the fact that this value had been previously tested for nullness,
+this is a definite possibility.
]]>
-
Possible null pointer dereference in method on exception pathPossible null pointer dereference of {2.givenClass} in {1} on exception path
@@ -4322,146 +5222,145 @@ be an exception path, since the default case is often infeasible.
]]>
-
- Possible null pointer dereference due to return value of called method
- Possible null pointer dereference in {1} due to return value of called method
-
+ Possible null pointer dereference due to return value of called method
+ Possible null pointer dereference in {1} due to return value of called method
+
A reference value which is null on some exception control path is
-dereferenced here. This may lead to a NullPointerException
-when the code is executed. The value may be null because it
-was returned from a method which is known to return possibly-null values.
+
The return value from a method is dereferenced without a null check,
+and the return value of that method is one that should generally be checked
+for null. This may lead to a NullPointerException when the code is executed.
+
]]>
-
- Non-virtual method call passes null for unconditionally dereferenced parameter
- Non-virtual method call in {1} passes null for unconditionally dereferenced parameter of {2.givenClass}
-
+ Non-virtual method call passes null for non-null parameter
+ Non-virtual method call in {1} passes null for non-null parameter of {2.givenClass}
+
- A possibly-null value is passed to a method which unconditionally
- dereferences it. This will almost certainly result in a null pointer exception.
+ A possibly-null value is passed to a non-null method parameter.
+ Either the parameter is annotated as a parameter that should
+ always be non-null, or analysis has shown that it will always be
+ dereferenced.
]]>
-
- Method call passes null for unconditionally dereferenced parameter
- Method call in {1} passes null for unconditionally dereferenced parameter of {2.givenClass}
-
+ Method call passes null for non-null parameter
+ Null passed for non-null parameter of {2.givenClass} in {1}
+
A possibly-null value is passed at a call site where all known
- target methods will unconditionally dereference it.
- This is very likely to result in a null pointer exception.
+ target methods require the parameter to be non-null.
+ Either the parameter is annotated as a parameter that should
+ always be non-null, or analysis has shown that it will always be
+ dereferenced.
]]>
-
- Method call passes null for unconditionally dereferenced parameter
- Method call in {1} passes null for unconditionally dereferenced parameter of {2.givenClass}
-
+ Method call passes null for non-null parameter
+ Null passed for non-null parameter of {2.givenClass} in {1}
+
- This method call passes a null value to a method which might
- dereference it unconditionally.
+ This method call passes a null value for a non-null method parameter.
+ Either the parameter is annotated as a parameter that should
+ always be non-null, or analysis has shown that it will always be
+ dereferenced.
]]>
-
- Method call passes null to a nonnull parameter
- Method call in {1} passes null to a nonnull parameter of {2.givenClass}
-
+ Method call passes null to a non-null parameter
+ Null passed for non-null parameter of {2.givenClass} in {1}
+
This method passes a null value as the parameter of a method which
- must be nonnull. Either this parameter has been explicitly marked
- as @Nonnull, or analysis has determined that this parameter is
- always dereferenced.
+ must be non-null. Either this parameter has been explicitly marked
+ as @Nonnull, or analysis has determined that this parameter is
+ always dereferenced.
]]>
-
- Method may return null, but is declared @NonNull
- Method {1} may return null, but is declared @NonNull
-
+ Method may return null, but is declared @Nonnull
+ {1} may return null, but is declared @Nonnull
+
This method may return a null value, but the method (or a superclass method
- which it overrides) is declared to return @NonNull.
+ which it overrides) is declared to return @Nonnull.
]]>
- Clone method may return null
- {1} may return null
-
+ Clone method may return null
+ {1} may return null
+
- This clone method seems to return null in some circumstances, but clone is never
- allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError
- instead.
+ This clone method seems to return null in some circumstances, but clone is never
+ allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError
+ instead.
]]>
- toString method may return null
- {1} may return null
-
+ toString method may return null
+ {1} may return null
+
- This toString method seems to return null in some circumstances. A liberal reading of the
- spec could be interpreted as allowing this, but it is probably a bad idea and could cause
- other code to break. Return the empty string or some other appropriate string rather than null.
+ This toString method seems to return null in some circumstances. A liberal reading of the
+ spec could be interpreted as allowing this, but it is probably a bad idea and could cause
+ other code to break. Return the empty string or some other appropriate string rather than null.
]]>
-
-
- Null value is guaranteed to be dereferenced
- {2.givenClass} could be null and is guaranteed to be dereferenced in {1}
-
-
- There is a statement or branch that if executed guarantees that
- a value is null at this point, and that
- value that is guaranteed to be dereferenced
- (except on forward paths involving runtime exceptions).
-
- ]]>
-
-
-
+ Null value is guaranteed to be dereferenced
+ {2.givenClass} could be null and is guaranteed to be dereferenced in {1}
+
+
+ There is a statement or branch that if executed guarantees that
+ a value is null at this point, and that
+ value that is guaranteed to be dereferenced
+ (except on forward paths involving runtime exceptions).
+
+
Note that a check such as
+ if (x == null) throw new NullPointerException();
+ is treated as a dereference of x.
+ ]]>
+
+
- Value is null and guaranteed to be dereferenced on exception path
- {2.name} is null guaranteed to be dereferenced in {1} on exception path
-
-
- There is a statement or branch on an exception path
- that if executed guarantees that
- a value is null at this point, and that
- value that is guaranteed to be dereferenced
- (except on forward paths involving runtime exceptions).
-
- ]]>
-
+ Value is null and guaranteed to be dereferenced on exception path
+ {2.name} is null guaranteed to be dereferenced in {1} on exception path
+
+
+ There is a statement or branch on an exception path
+ that if executed guarantees that
+ a value is null at this point, and that
+ value that is guaranteed to be dereferenced
+ (except on forward paths involving runtime exceptions).
+
+ ]]>
+
-
Static initializer creates instance before all static final fields assignedStatic initializer for {0} creates instance before all static final fields assigned
@@ -4472,14 +5371,13 @@ before all of the static final fields are assigned.
]]>
-
Method may fail to close stream{1} may fail to close stream
The method creates an IO stream object, does not assign it to any
-fields, pass it to other methods that might close it,
+fields, pass it to other methods that might close it,
or return it, and does not appear to close
the stream on all paths out of the method. This may result in
a file descriptor leak. It is generally a good
@@ -4488,7 +5386,6 @@ closed.
]]>
-
Method may fail to close stream on exception{1} may fail to close stream on exception
@@ -4503,7 +5400,6 @@ closed.
]]>
-
Consider returning a zero length array rather than nullShould {1} return a zero length array rather than null?
@@ -4522,7 +5418,6 @@ is not a directory.
]]>
-
Useless control flowUseless control flow in {1}
@@ -4532,11 +5427,11 @@ is not a directory.
control flow continues onto the same place regardless of whether or not
the branch is taken. For example,
this is caused by having an empty statement
-block fot an if statement:
+block for an if statement:
if (argv.length == 0) {
- // TODO: handle this case
- }
+ // TODO: handle this case
+ }
]]>
@@ -4558,7 +5453,6 @@ body of an if statement, e.g.:
]]>
-
Nullcheck of value previously dereferencedNullcheck of {2.givenClass} at {4.lineNumber} of value previously dereferenced in {1}
@@ -4566,7 +5460,7 @@ body of an if statement, e.g.:
A value is checked here to see whether it is null, but this value can't
be null because it was previously dereferenced and if it were null a null pointer
-exception would have occurred at the earlier dereference.
+exception would have occurred at the earlier dereference.
Essentially, this code and the previous dereference
disagree as to whether this value is allowed to be null. Either the check is redundant
or the previous dereference is erroneous.
@@ -4583,9 +5477,6 @@ the constant null.
]]>
-
-
-
Redundant nullcheck of value known to be non-nullRedundant nullcheck of {2}, which is known to be non-null in {1}
@@ -4606,8 +5497,6 @@ both be definitely null.
]]>
-
-
Redundant comparison of non-null value to nullRedundant comparison of non-null value to null in {1}
@@ -4618,10 +5507,8 @@ known to be null.
]]>
-
-
-
-
+
+
Redundant comparison to null of previously checked valueRedundant comparison to null of previously checked {2} in {1}
@@ -4641,7 +5528,6 @@ of defensive programming.
]]>
-
Method does not release lock on all paths{1} does not release lock on all paths
@@ -4663,7 +5549,6 @@ for using a JSR-166 lock is:
]]>
-
Method does not release lock on all exception paths{1} does not release lock on all exception paths
@@ -4685,7 +5570,6 @@ for using a JSR-166 lock is:
]]>
-
Suspicious reference comparisonSuspicious comparison of {2} references in {1}
@@ -4693,15 +5577,47 @@ for using a JSR-166 lock is:
This method compares two reference values using the == or != operator,
where the correct way to compare instances of this type is generally
-with the equals() method. Examples of classes which should generally
+with the equals() method.
+It is possible to create distinct instances that are equal but do not compare as == since
+they are different objects.
+Examples of classes which should generally
not be compared by reference are java.lang.Integer, java.lang.Float, etc.
]]>
-
+
+ Suspicious reference comparison to constant
+ Suspicious comparison of a {2} reference to constant in {1}
+
+ This method compares a reference value to a constant using the == or != operator,
+where the correct way to compare instances of this type is generally
+with the equals() method.
+It is possible to create distinct instances that are equal but do not compare as == since
+they are different objects.
+Examples of classes which should generally
+not be compared by reference are java.lang.Integer, java.lang.Float, etc.
+]]>
+
+
+
+ Suspicious reference comparison of Boolean values
+ Suspicious comparison of Boolean references in {1}
+
+ This method compares two Boolean values using the == or != operator.
+Normally, there are only two Boolean values (Boolean.TRUE and Boolean.FALSE),
+but it is possible to create other Boolean objects using the new Boolean(b)
+constructor. It is best to avoid such objects, but if they do exist,
+then checking Boolean objects for equality using == or != will give results
+than are different than you would get using .equals(...)
+
+]]>
+
+
- Using pointer equality to compare different types
- Using pointer equality to compare a {2} with a {3} in {1}
+ Using pointer equality to compare different types
+ Using pointer equality to compare a {2.givenClass} with a {3.givenClass} in {1}
This method uses using pointer equality to compare two references that seem to be of
@@ -4712,28 +5628,22 @@ different types. The result of this comparison will always be false at runtime.
Call to equals() comparing different types
- Call to equals() comparing different types in {1}
+ Call to {3.simpleClass}.equals({2.simpleClass}) in {1}
This method calls equals(Object) on two references of different
-class types with no common subclasses.
-Therefore, the objects being compared
-are unlikely to be members of the same class at runtime
-(unless some application classes were not analyzed, or dynamic class
-loading can occur at runtime).
-According to the contract of equals(),
-objects of different
-classes should always compare as unequal; therefore, according to the
-contract defined by java.lang.Object.equals(Object),
-the result of this comparison will always be false at runtime.
+class types and analysis suggests they will be to objects of different classes
+at runtime. Further, examination of the equals methods that would be invoked suggest that either
+this call will always return false, or else the equals method is not be symmetric (which is
+a property required by the contract
+for equals in class Object).
]]>
-
Call to equals() comparing different interface types
- Call to equals() comparing different interface types in {1}
+ Call to {3.simpleClass}.equals({2.simpleClass}) in {1}
This method calls equals(Object) on two references of unrelated
@@ -4752,11 +5662,10 @@ the result of this comparison will always be false at runtime.
]]>
-
- Call to equals() comparing unrelated class and interface
- Call to equals() comparing unrelated class and interface in {1}
-
+ Call to equals() comparing unrelated class and interface
+ Call to {3.simpleClass}.equals({2.simpleClass}) in {1}
+
This method calls equals(Object) on two references, one of which is a class
@@ -4775,11 +5684,9 @@ the result of this comparison will always be false at runtime.
]]>
-
-
- Call to equals() with null argument
- Call to equals() with null argument in {1}
+ Call to equals(null)
+ Call to equals(null) in {1}
This method calls equals(Object), passing a null value as
@@ -4788,7 +5695,6 @@ this call should always return false.
]]>
-
Mismatched wait()Mismatched wait() in {1}
@@ -4800,7 +5706,6 @@ an IllegalMonitorStateException being thrown.
]]>
-
Mismatched notify()Mismatched notify() in {1}
@@ -4812,10 +5717,27 @@ an IllegalMonitorStateException being thrown.
]]>
-
+
+ Self assignment of local rather than assignment to field
+ Self assignment of {2} rather than assigned to field in {1}
+
+ This method contains a self assignment of a local variable, and there
+is a field with an identical name.
+assignment appears to have been ; e.g.
+
+ int foo;
+ public void setFoo(int foo) {
+ foo = foo;
+ }
+
+
The assignment is useless. Did you mean to assign to the field instead?
+]]>
+
+ Self assignment of local variable
- Self assignment of local variable in {1}
+ Self assignment of {2} in {1}
This method contains a self assignment of a local variable; e.g.
@@ -4831,7 +5753,6 @@ Such assignments are useless, and may indicate a logic error or typo.
]]>
-
Self assignment of fieldSelf assignment of field {2.givenClass} in {1}
@@ -4849,7 +5770,6 @@ Such assignments are useless, and may indicate a logic error or typo.
]]>
-
Double assignment of fieldDouble assignment of field {2.givenClass} in {1}
@@ -4880,14 +5800,13 @@ Such assignments are useless, and may indicate a logic error or typo.
x = x = 17;
}
-
Assigning the same value to a variable twice is useless, and may indicate a logic error or typo.
+
Assigning the same value to a variable twice is useless, and may indicate a logic error or typo.
]]>
-
Nonsensical self computation involving a field (e.g., x & x)
- Nonsensical self computation of {2.givenClass} with itself {1}
+ Nonsensical self computation of {2.givenClass} with itself in {1}
This method performs a nonsensical computation of a field with another
@@ -4901,7 +5820,7 @@ a logic error. Double check the computation.
Nonsensical self computation involving a variable (e.g., x & x)
- Nonsensical self computation of {2} with itself {1}
+ Nonsensical self computation of {2} with itself in {1}
This method performs a nonsensical computation of a local variable with another
@@ -4913,11 +5832,9 @@ a logic error. Double check the computation.
]]>
-
-
Self comparison of field with itself
- Self comparison of {2.givenClass} with itself {1}
+ Self comparison of {2.givenClass} with itself in {1}
This method compares a field with itself, and may indicate a typo or
@@ -4926,7 +5843,6 @@ a logic error. Make sure that you are comparing the right things.
]]>
-
Self comparison of value with itselfSelf comparison of {2} with itself {1}
@@ -4938,30 +5854,37 @@ a logic error. Make sure that you are comparing the right things.
]]>
-
Double.longBitsToDouble invoked on an intDouble.longBitsToDouble invoked on an int in {1}
The Double.longBitsToDouble method is invoked, but a 32 bit int value is passed
- as an argument. This almostly certainly is not intended and is unlikely
- to give the intended result.
+ as an argument. This almostly certainly is not intended and is unlikely
+ to give the intended result.
+
+]]>
+
+
+
+ Reversed method arguments
+ Arguments in wrong order for invocation of {2.name} in {1}
+
+ The arguments to this method call seem to be in the wrong order.
+For example, a call Preconditions.checkNotNull("message", message)
+has reserved arguments: the value to be checked is the first argument.
]]>
-
-
-
-
Random object created and used only onceRandom object created and used only once in {1}
This code creates a java.util.Random object, uses it to generate one random number, and then discards
-the Random object. This produces mediocre quality random numbers and is inefficient.
+the Random object. This produces mediocre quality random numbers and is inefficient.
If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number
is required invoke a method on the existing Random object to obtain it.
@@ -4974,37 +5897,34 @@ number; the values are too easily guessable. You should strongly consider using
- Bad attempt to compute absolute value of signed 32-bit random integer
- Bad attempt to compute absolute value of signed 32-bit random integer in {1}
+ Bad attempt to compute absolute value of signed random integer
+ Bad attempt to compute absolute value of signed random integer in {1}
This code generates a random signed integer and then computes
the absolute value of that random integer. If the number returned by the random number
-generator is Integer.MIN_VALUE, then the result will be negative as well (since
-Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE).
+generator is Integer.MIN_VALUE, then the result will be negative as well (since
+Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE). (Same problem arised for long values as well).
]]>
-
-
-
Bad attempt to compute absolute value of signed 32-bit hashcode Bad attempt to compute absolute value of signed 32-bit hashcode in {1}
This code generates a hashcode and then computes
-the absolute value of that hashcode. If the hashcode
-is Integer.MIN_VALUE, then the result will be negative as well (since
+the absolute value of that hashcode. If the hashcode
+is Integer.MIN_VALUE, then the result will be negative as well (since
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE).
+
One out of 2^32 strings have a hashCode of Integer.MIN_VALUE,
+including "polygenelubricants" "GydZG_" and ""DESIGNING WORKHOUSES".
+
]]>
-
-
-
Remainder of 32-bit signed random integerRemainder of 32-bit signed random integer computed in {1}
@@ -5019,7 +5939,6 @@ consider using the Random.nextInt(int) method instead.
]]>
-
Remainder of hashCode could be negativeRemainder of hashCode could be negative in {1}
@@ -5033,7 +5952,7 @@ can also be negative.
you may need to change your code.
If you know the divisor is a power of 2,
you can use a bitwise and operator instead (i.e., instead of
-using x.hashCode()%n, use x.hashCode()&(n-1).
+using x.hashCode()%n, use x.hashCode()&(n-1).
This is probably faster than computing the remainder as well.
If you don't know that the divisor is a power of 2, take the absolute
value of the result of the remainder operation (i.e., use
@@ -5042,20 +5961,17 @@ value of the result of the remainder operation (i.e., use
]]>
-
-
- Bad comparison of nonnegative value with negative constant
+ Bad comparison of nonnegative value with negative constant or zeroBad comparison of nonnegative value with {2} in {1}
This code compares a value that is guaranteed to be non-negative with a negative constant.
+
This code compares a value that is guaranteed to be non-negative with a negative constant or zero.
]]>
-
Bad comparison of signed byteBad comparison of signed byte with {2} in {1}
@@ -5066,12 +5982,35 @@ a signed byte with a value outside that range is vacuous and likely to be incorr
To convert a signed byte b to an unsigned value in the range 0..255,
use 0xff & b
+]]>
+
+
+
+ Bad comparison of int value with long constant
+ Bad comparison of int with {2} in {1}
+
+ This code compares an int value with a long constant that is outside
+the range of values that can be represented as an int value.
+This comparison is vacuous and possibily to be incorrect.
+
]]>
+
+ Vacuous bit mask operation on integer value
+ Vacuous {2} operation on {3} in {1}
+
+ This is an integer bit operation (and, or, or exclusive or) that doesn't do any useful work
+(e.g., v & 0xffffffff).
+
+]]>
+
+ Vacuous comparison of integer valueVacuous comparison of integer value {1}
@@ -5099,57 +6038,86 @@ Did you mean (exp & 1) or (exp % 2) instead?
Bitwise OR of signed byte value computed in {1}
Loads a value from a byte array and performs a bitwise OR with
-that value. Values loaded from a byte array are sign extended to 32 bits
+
Loads a byte value (e.g., a value loaded from a byte array or returned by a method
+with return type byte) and performs a bitwise OR with
+that value. Byte values are sign extended to 32 bits
+before any any bitwise operations are performed on the value.
+Thus, if b[0] contains the value 0xff, and
+x is initially 0, then the code
+((x << 8) | b[0]) will sign extend 0xff
+to get 0xffffffff, and thus give the value
+0xffffffff as the result.
+
+
+
In particular, the following code for packing a byte array into an int is badly wrong:
+
+int result = 0;
+for(int i = 0; i < 4; i++)
+ result = ((result << 8) | b[i]);
+
+
+
The following idiom will work instead:
+
+int result = 0;
+for(int i = 0; i < 4; i++)
+ result = ((result << 8) | (b[i] & 0xff));
+
+
+]]>
+
+
+
+ Bitwise add of signed byte value
+ Bitwise add of signed byte value computed in {1}
+
+ Adds a byte value and a value which is known to have the 8 lower bits clear.
+Values loaded from a byte array are sign extended to 32 bits
before any any bitwise operations are performed on the value.
Thus, if b[0] contains the value 0xff, and
-x is initially 0, then the code
-((x << 8) | b[0]) will sign extend 0xff
+x is initially 0, then the code
+((x << 8) + b[0]) will sign extend 0xff
to get 0xffffffff, and thus give the value
0xffffffff as the result.
In particular, the following code for packing a byte array into an int is badly wrong:
-
+
int result = 0;
-for(int i = 0; i < 4; i++)
- result = ((result << 8) | b[i]);
-
+for(int i = 0; i < 4; i++)
+ result = ((result << 8) + b[i]);
+
The following idiom will work instead:
-
+
int result = 0;
-for(int i = 0; i < 4; i++)
- result = ((result << 8) | (b[i] &s; 0xff));
-
+for(int i = 0; i < 4; i++)
+ result = ((result << 8) + (b[i] & 0xff));
+
]]>
-
-
-
Incompatible bit masks
- Incompatible bit masks yield a constant result in {1}
+ Incompatible bit masks in (e & {2} == {3}) yields a constant result in {1}
This method compares an expression of the form (a & C) to D,
+
This method compares an expression of the form (e & C) to D,
which will always compare unequal
due to the specific values of constants C and D.
This may indicate a logic error or typo.
]]>
-
Check for sign of bitwise operationCheck for sign of bitwise operation in {1}
This method compares an expression such as
+
This method compares an expression such as
((event.detail & SWT.SELECTED) > 0)
.
-Using bit arithmetic and then comparing with the greater than operator can
+
Using bit arithmetic and then comparing with the greater than operator can
lead to unexpected results (of course depending on the value of
SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate
for a bug. Even when SWT.SELECTED is not negative, it seems good practice
@@ -5161,15 +6129,14 @@ to use '!= 0' instead of '> 0'.
]]>
-
Check for sign of bitwise operationCheck for sign of bitwise operation in {1}
This method compares an expression such as
+
This method compares an expression such as
((event.detail & SWT.SELECTED) > 0)
.
-Using bit arithmetic and then comparing with the greater than operator can
+
Using bit arithmetic and then comparing with the greater than operator can
lead to unexpected results (of course depending on the value of
SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate
for a bug. Even when SWT.SELECTED is not negative, it seems good practice
@@ -5181,27 +6148,23 @@ to use '!= 0' instead of '> 0'.
]]>
-
-
-
Check to see if ((...) & 0) == 0Check to see if ((...) & 0) == 0 in {1}
This method compares an expression of the form (a & 0) to 0,
+
This method compares an expression of the form (e & 0) to 0,
which will always compare equal.
This may indicate a logic error or typo.
]]>
-
Incompatible bit masks
- Incompatible bit masks yield a constant result in {1}
+ Incompatible bit masks in (e | {2} == {3}) yields constant result in {1}
This method compares an expression of the form (a | C) to D.
+
This method compares an expression of the form (e | C) to D.
which will always compare unequal
due to the specific values of constants C and D.
This may indicate a logic error or typo.
@@ -5212,8 +6175,8 @@ operator ("|") instead of bitwise AND ("&").
]]>
-
-
+
+
Incorrect lazy initialization of instance fieldIncorrect lazy initialization of instance field {2} in {1}
@@ -5229,7 +6192,6 @@ For more information, see the
]]>
-
Incorrect lazy initialization of static fieldIncorrect lazy initialization of static field {2} in {1}
@@ -5252,33 +6214,72 @@ For more information, see the
This method contains an unsynchronized lazy initialization of a static field.
-After the field is set, the object stored into that location is further accessed.
+After the field is set, the object stored into that location is further updated or accessed.
The setting of the field is visible to other threads as soon as it is set. If the
futher accesses in the method that set the field serve to initialize the object, then
you have a very serious multithreading bug, unless something else prevents
any other thread from accessing the stored object until it is fully initialized.
+
Even if you feel confident that the method is never called by multiple
+threads, it might be better to not set the static field until the value
+you are setting it to is fully populated/initialized.
]]>
-
- Synchronization performed on java.util.concurrent Lock
- Synchronization performed on java.util.concurrent Lock in {1}
-
+ Synchronization performed on Lock
+ Synchronization performed on {2} in {1}
+
This method performs synchronization on an implementation of
-java.util.concurrent.locks.Lock. You should use
-the lock() and unlock() methods instead.
+
This method performs synchronization an object that implements
+java.util.concurrent.locks.Lock. Such an object is locked/unlocked
+using
+acquire()/release() rather
+than using the synchronized (...) construct.
+
+]]>
+
+
+
+ Using monitor style wait methods on util.concurrent abstraction
+ Calling {2.name} rather than {3.name} in {1}
+
+ This method calls
+wait(),
+notify() or
+notifyAll()()
+on an object that also provides an
+await(),
+signal(),
+signalAll() method (such as util.concurrent Condition objects).
+This probably isn't what you want, and even if you do want it, you should consider changing
+your design, as other developers will find it exceptionally confusing.
+
+]]>
+
+
+
+ Synchronization performed on util.concurrent instance
+ Synchronization performed on {2} in {1}
+
+ This method performs synchronization an object that is an instance of
+a class from the java.util.concurrent package (or its subclasses). Instances
+of these classes have their own concurrency control mechanisms that are orthogonal to
+the synchronization provided by the Java keyword synchronized. For example,
+synchronizing on an AtomicBoolean will not prevent other threads
+from modifying the AtomicBoolean.
+
Such code may be correct, but should be carefully reviewed and documented,
+and may confuse people who have to maintain the code at a later date.
]]>
-
Private method is never calledPrivate method {1} is never called
-
+
This private method is never called. Although it is
possible that the method will be invoked through reflection,
@@ -5291,7 +6292,7 @@ removed.
Uncallable method defined in anonymous classUncallable method {1} defined in anonymous class
-
+
This anonymous class defined a method that is not directly invoked and does not override
a method in a superclass. Since methods in other classes cannot directly invoke methods
@@ -5303,7 +6304,6 @@ in fact, override the method it is intended to.
]]>
-
Method may fail to close database resource{1} may fail to close {2.excludingPackage}
@@ -5320,7 +6320,6 @@ have problems communicating with the database.
]]>
-
Method may fail to close database resource on exception{1} may fail to close database resource on exception
@@ -5336,10 +6335,9 @@ have problems communicating with the database.
]]>
-
Method concatenates strings using + in a loop
- Method {1} concatenates strings using + in a loop
+ {1} concatenates strings using + in a loop
The method seems to be building a String using concatenation in a loop.
@@ -5369,10 +6367,75 @@ a StringBuffer (or StringBuilder in Java 1.5) explicitly.
]]>
-
+
+ Method calls prepareStatement in a loop
+ {1} calls prepareStatement with the constant arguments in a loop
+
+ The method calls Connection.prepareStatement inside the loop passing the constant arguments.
+If the PreparedStatement should be executed several times there's no reason to recreate it for each loop iteration.
+Move this call outside of the loop.
+]]>
+
+
+
+ NodeList.getLength() called in a loop
+ {1} calls NodeList.getLength() in a loop for getElementsByTagName return value
+
+ The method calls NodeList.getLength() inside the loop and NodeList was produced by getElementsByTagName call.
+This NodeList doesn't store its length, but computes it every time in not very optimal way.
+Consider storing the length to the variable before the loop.
+
+]]>
+
+
+
+ Method calls Pattern.compile in a loop
+ {1} calls Pattern.compile with the constant arguments in a loop
+
+ The method calls Pattern.compile inside the loop passing the constant arguments.
+If the Pattern should be used several times there's no reason to compile it for each loop iteration.
+Move this call outside of the loop or even into static final field.
+]]>
+
+
+
+ Method compiles the regular expression in a loop
+ {1} compiles the regular expression in a loop
+
+ The method creates the same regular expression inside the loop, so it will be compiled every iteration.
+It would be more optimal to precompile this regular expression using Pattern.compile outside of the loop.
+]]>
+
+
+
+ Inefficient use of String.indexOf(String)
+ {1} uses String.indexOf(String) instead of String.indexOf(int)
+
+ This code passes a constant string of length 1 to String.indexOf().
+It is more efficient to use the integer implementations of String.indexOf().
+f. e. call myString.indexOf('.') instead of myString.indexOf(".")
+]]>
+
+
+
+ Inefficient use of String.lastIndexOf(String)
+ {1} uses String.lastIndexOf(String) instead of String.lastIndexOf(int)
+
+ This code passes a constant string of length 1 to String.lastIndexOf().
+It is more efficient to use the integer implementations of String.lastIndexOf().
+f. e. call myString.lastIndexOf('.') instead of myString.lastIndexOf(".")
+]]>
+
+ Method uses toArray() with zero-length array argument
- Method {1} uses Collection.toArray() with zero-length array argument
+ {1} uses Collection.toArray() with zero-length array argument
This method uses the toArray() method of a collection derived class, and passes
@@ -5385,7 +6448,6 @@ directly. This avoids the need to create a second array
]]>
-
JUnit assertion in run method will not be noticed by JUnitJUnit assertion in {1} will not be noticed by JUnit
@@ -5401,8 +6463,8 @@ in the test failing.
- TestCase implements setUp but doesn't call super.setUp()
- TestCase {0} implements setUp but doesn't call super.setUp()
+ TestCase defines setUp that doesn't call super.setUp()
+ TestCase {0} defines setUp that doesn't call super.setUp()
Class is a JUnit TestCase and implements the setUp method. The setUp method should call
@@ -5410,10 +6472,9 @@ super.setUp(), but doesn't.
]]>
-
- TestCase implements tearDown but doesn't call super.tearDown()
- TestCase {0} implements tearDown but doesn't call super.tearDown()
+ TestCase defines tearDown that doesn't call super.tearDown()
+ TestCase {0} defines tearDown that doesn't call super.tearDown()
Class is a JUnit TestCase and implements the tearDown method. The tearDown method should call
@@ -5421,7 +6482,6 @@ super.tearDown(), but doesn't.
]]>
-
TestCase implements a non-static suite method TestCase {0} implements a non-static suite method
@@ -5432,22 +6492,19 @@ super.tearDown(), but doesn't.
]]>
-
TestCase declares a bad suite method Bad declaration for suite method in {0}
Class is a JUnit TestCase and defines a suite() method.
-However, the suite method needs to be declared as either
+However, the suite method needs to be declared as either
public static junit.framework.Test suite()
-or
+or
public static junit.framework.TestSuite suite()
-
]]>
-
TestCase has no testsTestCase {0} has no tests
@@ -5457,8 +6514,6 @@ or
]]>
-
-
Class overrides a method implemented in super class Adapter wronglyClass {0} overrides a method {1} implemented in super class Adapter wrongly
@@ -5470,10 +6525,10 @@ get called when the event occurs.
]]>
-
-
+
+
Method attempts to access a result set field with index 0
- Method {1} attempts to access a result set field with index 0
+ {1} attempts to access a result set field with index 0
A call to getXXX or updateXXX methods of a result set was made where the
@@ -5481,10 +6536,9 @@ field index is 0. As ResultSet fields start at index 1, this is always a mistake
]]>
-
Method attempts to access a result set field with index 0
- Method {1} attempts to access a result set field with index 0
+ {1} attempts to access a result set field with index 0
A call to getXXX or updateXXX methods of a result set was made where the
@@ -5492,10 +6546,9 @@ field index is 0. As ResultSet fields start at index 1, this is always a mistake
]]>
-
Method attempts to access a prepared statement parameter with index 0
- Method {1} attempts to access a prepared statement parameter with index 0
+ {1} attempts to access a prepared statement parameter with index 0
A call to a setXXX method of a prepared statement was made where the
@@ -5503,10 +6556,9 @@ parameter index is 0. As parameter indexes start at index 1, this is always a mi
]]>
-
Unnecessary type check done using instanceof operator
- Method {1} does an unnecessary type check using instanceof operator when it can be determined statically
+ {1} does an unnecessary type check using instanceof operator when it can be determined statically
Type check performed using the instanceof operator where it can be statically determined whether the object
@@ -5514,7 +6566,6 @@ is of the type requested.
]]>
-
Bad Applet Constructor relies on uninitialized AppletStubBad Applet Constructor relies on uninitialized AppletStub
@@ -5528,10 +6579,9 @@ correctly.
]]>
-
equals() used to compare array and nonarray
- {1} uses equals to compare an array and nonarray
+ Calling {3.simpleClass}.equals({2.simpleClass}) in {1}
@@ -5547,40 +6597,36 @@ contents of the arrays, use java.util.Arrays.equals(Object[], Object[]).
Invocation of equals() on an array, which is equivalent to ==
- {1} invokes equals() on an array, which is equivalent to ==
+ Using .equals to compare two {2.simpleClass}'s, (equivalent to ==) in {1}
This method invokes the .equals(Object o) method on an array. Since arrays do not override the equals
method of Object, calling equals on an array is the same as comparing their addresses. To compare the
-contents of the arrays, use java.util.Arrays.equals(Object[], Object[]).
+contents of the arrays, use java.util.Arrays.equals(Object[], Object[]).
+To compare the addresses of the arrays, it would be
+less confusing to explicitly check pointer equality using ==.
]]>
-
-
- Calls to equals on a final class that doesn't override Object's version
- Calls to equals on a final class that doesn't override Object's version
+
+ equals(...) used to compare incompatible arrays
+ Using equals to compare a {2.simpleClass} and a {3.simpleClass} in {1}
-This method invokes the .equals(Object o) method on a final class that doesn't override the equals method
-in the Object class, effectively making the equals method test for sameness, like ==. It is good to use
-the .equals method, but you should consider adding an .equals method in this class.
-
-
[Bill Pugh]: Sorry, but I strongly disagree that this should be a warning, and I think your code
-is just fine. Users of your code shouldn't care how you've implemented equals(), and they should never
-depend on == to compare instances, since that bypasses the libraries ability to control how objects
-are compared.
+This method invokes the .equals(Object o) to compare two arrays, but the arrays of
+of incompatible types (e.g., String[] and StringBuffer[], or String[] and int[]).
+They will never be equal. In addition, when equals(...) is used to compare arrays it
+only checks to see if they are the same array, and ignores the contents of the arrays.
]]>
-
Unneeded use of currentThread() call, to call interrupted()
- Method {1} makes an unneeded call to currentThread() just to call interrupted()
+ {1} makes an unneeded call to currentThread() just to call interrupted()
@@ -5590,7 +6636,6 @@ static method, is more simple and clear to use Thread.interrupted().
]]>
-
Static Thread.interrupted() method invoked on thread instance{1} invokes static Thread.interrupted() method on thread instance
@@ -5604,7 +6649,6 @@ object than the one the author intended.
]]>
-
A parameter is dead upon entry to a method but overwrittenThe parameter {2} to {1} is dead upon entry but overwritten
@@ -5616,6 +6660,21 @@ is overwritten here. This often indicates a mistaken belief that
the write to the parameter will be conveyed back to
the caller.
+]]>
+
+
+
+ Dead store to local variable that shadows field
+ Dead store to {2} rather than field with same name in {1}
+
+
+This instruction assigns a value to a local variable,
+but the value is not read or used in any subsequent instruction.
+Often, this indicates an error, because the value computed is never
+used. There is a field with the same name as the local variable. Did you
+mean to assign to that variable instead?
+
]]>
@@ -5638,19 +6697,35 @@ there is no easy way to eliminate these false positives.
]]>
+
Useless assignment in return statementUseless assignment in return from {1}
-This statement assigns to a local variable in a return statement. This assignment
+This statement assigns to a local variable in a return statement. This assignment
has effect. Please verify that this statement does the right thing.
]]>
-
+
+ Useless increment in return statement
+ Useless increment in return from {1}
+
+ This statement has a return such as return x++;.
+A postfix increment/decrement does not impact the value of the expression,
+so this increment/decrement has no effect.
+Please verify that this statement does the right thing.
+
+]]>
+
+
+
+
+
Dead store of class literalDead store of {3}.class in {1}
@@ -5669,7 +6744,6 @@ for more details and examples, and suggestions on how to force class initializat
]]>
-
Dead store of null to local variableDead store of null to {2} in {1}
@@ -5682,10 +6756,9 @@ as of Java SE 6.0, this is no longer needed or useful.
]]>
-
-
+ Method defines a variable that obscures a field
- Method {1} defines a variable that obscures field {2.givenClass}
+ {1} defines a variable that obscures field {2.givenClass}
This method defines a local variable with the same name as a field
@@ -5695,7 +6768,6 @@ or both.
]]>
-
Class defines field that masks a superclass fieldField {1.givenClass} masks field in superclass {2.class}
@@ -5708,34 +6780,31 @@ the fields when they wanted the other.
]]>
-
-
- Inefficient use of keySet iterator instead of entrySet iterator
- Method {1} makes inefficient use of keySet iterator instead of entrySet iterator
-
+
+ Inefficient use of keySet iterator instead of entrySet iterator
+ {1} makes inefficient use of keySet iterator instead of entrySet iterator
+
This method accesses the value of a Map entry, using a key that was retrieved from
a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the
Map.get(key) lookup.
]]>
-
-
-
- Needless instantiation of class that only supplies static methods
- Method {1} needlessly instantiates a class that only supplies static methods
-
+
+
+ Needless instantiation of class that only supplies static methods
+ {1} needlessly instantiates a class that only supplies static methods
+
This class allocates an object that is based on a class that only supplies static methods. This object
does not need to be created, just access the static methods directly using the class name as a qualifier.
]]>
-
-
-
- Exception is caught when Exception is not thrown
- Exception is caught when Exception is not thrown in {1}
-
+
+
+ Exception is caught when Exception is not thrown
+ Exception is caught when Exception is not thrown in {1}
+
This method uses a try-catch block that catches Exception objects, but Exception is not
@@ -5744,34 +6813,43 @@ does not need to be created, just access the static methods directly using the c
each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well,
masking potential bugs.
+
A better approach is to either explicitly catch the specific exceptions that are thrown,
+ or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
]]>
-
-
-
- Doomed test for equality to NaN
- Doomed test for equality to NaN in {1}
-
+
+
+ Doomed test for equality to NaN
+ Doomed test for equality to NaN in {1}
+
This code checks to see if a floating point value is equal to the special
- Not A Number value (e.g., if (x == Double.NaN)). However,
- because of the special semantics of NaN, no value
- is equal to Nan, including NaN. Thus,
- x == Double.NaN always evaluates to false.
-
- To check to see if a value contained in x
- is the special Not A Number value, use
- Double.isNaN(x) (or Float.isNaN(x) if
- x is floating point precision).
+ Not A Number value (e.g., if (x == Double.NaN)). However,
+ because of the special semantics of NaN, no value
+ is equal to Nan, including NaN. Thus,
+ x == Double.NaN always evaluates to false.
+
+ To check to see if a value contained in x
+ is the special Not A Number value, use
+ Double.isNaN(x) (or Float.isNaN(x) if
+ x is floating point precision).
]]>
-
-
- Test for floating point equality
- Test for floating point equality in {1}
-
+
+
+ Test for floating point equality
+ Test for floating point equality in {1}
+
This operation compares two floating point values for equality.
@@ -5786,8 +6864,7 @@ does not need to be created, just access the static methods directly using the c
]]>
-
-
+ Method calls static Math class method on a constant valueMethod calls static Math class method on a constant value
@@ -5874,11 +6951,10 @@ just use the constant. Methods detected are:
]]>
-
-
- Test for circular dependencies among classes
- Class {0} has a circular dependency with other classes
-
+
+ Test for circular dependencies among classes
+ Class {0} has a circular dependency with other classes
+
This class has a circular dependency with other classes. This makes building these classes
@@ -5887,12 +6963,11 @@ just use the constant. Methods detected are:
]]>
-
-
-
- Class implements same interface as superclass
- Class {0} implements same interface as superclass
-
+
+
+ Class implements same interface as superclass
+ Class {0} implements same interface as superclass
+
This class declares that it implements an interface that is also implemented by a superclass.
@@ -5903,28 +6978,26 @@ just use the constant. Methods detected are:
]]>
-
-
-
- Class extends Struts Action class and uses instance variables
- Class {0} extends Struts Action class and uses instance variables
-
+
+
+ Class extends Struts Action class and uses instance variables
+ Class {0} extends Struts Action class and uses instance variables
+
This class extends from a Struts Action class, and uses an instance member variable. Since only
one instance of a struts Action class is created by the Struts framework, and used in a
multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider
only using method local variables. Only instance fields that are written outside of a monitor
- are reported.
+ are reported.
]]>
-
-
-
- Class extends Servlet class and uses instance variables
- Class {0} extends Servlet class and uses instance variables
-
+
+
+ Class extends Servlet class and uses instance variables
+ Class {0} extends Servlet class and uses instance variables
+
This class extends from a Servlet class, and uses an instance member variable. Since only
@@ -5934,12 +7007,11 @@ just use the constant. Methods detected are:
]]>
-
-
-
- Class exposes synchronization and semaphores in its public interface
- Class {0} exposes synchronization and semaphores in its public interface
-
+
+
+ Class exposes synchronization and semaphores in its public interface
+ Class {0} exposes synchronization and semaphores in its public interface
+
This class uses synchronization along with wait(), notify() or notifyAll() on itself (the this
@@ -5950,8 +7022,7 @@ just use the constant. Methods detected are:
]]>
-
-
+ Result of integer multiplication cast to longResult of integer multiplication cast to long in {1}
@@ -5959,30 +7030,56 @@ just use the constant. Methods detected are:
This code performs integer multiply and then converts the result to a long,
-as in:
-
-
- long convertDaysToMilliseconds(int days) { return 1000*3600*24*days; }
-
+as in:
+
+ long convertDaysToMilliseconds(int days) { return 1000*3600*24*days; }
+
+
If the multiplication is done using long arithmetic, you can avoid
the possibility that the result will overflow. For example, you
-could fix the above code to:
-
-
- long convertDaysToMilliseconds(int days) { return 1000L*3600*24*days; }
-
-or
-
-
- static final long MILLISECONDS_PER_DAY = 24L*3600*1000;
- long convertDaysToMilliseconds(int days) { return days * MILLISECONDS_PER_DAY; }
-
-
-
+could fix the above code to:
+
+ long convertDaysToMilliseconds(int days) { return 1000L*3600*24*days; }
+
+or
+
+ static final long MILLISECONDS_PER_DAY = 24L*3600*1000;
+ long convertDaysToMilliseconds(int days) { return days * MILLISECONDS_PER_DAY; }
+
]]>
+
+ int value converted to long and used as absolute time
+ int converted to long and passed as absolute time to {2} in {1}
+
+
+This code converts a 32-bit int value to a 64-bit long value, and then
+passes that value for a method parameter that requires an absolute time value.
+An absolute time value is the number
+of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
+For example, the following method, intended to convert seconds since the epoch into a Date, is badly
+broken:
+
The multiplication is done using 32-bit arithmetic, and then converted to a 64-bit value.
+When a 32-bit value is converted to 64-bits and used to express an absolute time
+value, only dates in December 1969 and January 1970 can be represented.
+
+
Correct implementations for the above method are:
+
+
+// Fails for dates after 2037
+Date getDate(int seconds) { return new Date(seconds * 1000L); }
+// better, works for all dates
+Date getDate(long seconds) { return new Date(seconds * 1000); }
+
+]]>
+
+ int value cast to float and then passed to Math.roundint value cast to float and then passed to Math.round in {1}
@@ -5995,21 +7092,21 @@ passing the result to the Math.round() function, which returns the int/long clos
to the argument. This operation should always be a no-op,
since the converting an integer to a float should give a number with no fractional part.
It is likely that the operation that generated the value to be passed
-to Math.round was intended to be performed using
+to Math.round was intended to be performed using
floating point arithmetic.
]]>
-
- int value cast to double and then passed to Math.ceil
- int value cast to double and then passed to Math.ceil in {1}
+ Integral value cast to double and then passed to Math.ceil
+ Integral value cast to double and then passed to Math.ceil in {1}
-This code converts an int value to a double precision
+This code converts an integral value (e.g., int or long)
+to a double precision
floating point number and then
passing the result to the Math.ceil() function, which rounds a double to
the next higher integer value. This operation should always be a no-op,
@@ -6022,14 +7119,14 @@ floating point arithmetic.
]]>
-
- int division result cast to double or float
- int division result cast to double or float in {1}
+ Integral division result cast to double or float
+ Integral division result cast to double or float in {1}
-This code casts the result of an integer division operation to double or
+This code casts the result of an integral division (e.g., int or long division)
+operation to double or
float.
Doing division on integers truncates the result
to the integer value closest to zero. The fact that the result
@@ -6051,7 +7148,6 @@ double value2 = x / (double) y;
]]>
-
Store of non serializable object into HttpSessionStore of non serializable {2} into HttpSession in {1}
@@ -6076,7 +7172,76 @@ If the object is, indeed, non-serializable, an error will result.
]]>
-
+
+ No previous argument for format string
+ No previous argument for format string argument to {2} in {1}
+
+
+The format string specifies a relative index to request that the argument for the previous format specifier
+be reused. However, there is no previous argument.
+For example,
+
+
formatter.format("%<s %s", "a", "b")
+
+
would throw a MissingFormatArgumentException when executed.
+
+]]>
+
+
+
+ Format string should use %n rather than \n
+ Format string should use %n rather than \n in {1}
+
+
+This format string include a newline character (\n). In format strings, it is generally
+ preferable better to use %n, which will produce the platform-specific line separator.
+
+]]>
+
+
+
+ The type of a supplied argument doesn't match format specifier
+ Argument of type {3} can't be handled by format specifier {4} in {1}
+
+
+One of the arguments is uncompatible with the corresponding format string specifier.
+As a result, this will generate a runtime exception when executed.
+For example, String.format("%d", "1") will generate an exception, since
+the String "1" is incompatible with the format specifier %d.
+
+]]>
+
+
+
+ Non-Boolean argument formatted using %b format specifier
+ Non-Boolean argument formatted using %b format specifier in {1}
+
+
+An argument not of type Boolean is being formatted with a %b format specifier. This won't throw an
+exception; instead, it will print true for any non-null value, and false for null.
+This feature of format strings is strange, and may not be what you intended.
+
+]]>
+
+
+
+ Array formatted in useless way using format string
+ Argument of type {3} formatted in useless way in {1}
+
+
+One of the arguments being formatted with a format string is an array. This will be formatted
+using a fairly useless format, such as [I@304282, which doesn't actually show the contents
+of the array.
+Consider wrapping the array using Arrays.asList(...) before handling it off to a formatted.
+
+]]>
+
+ Number of format-string arguments does not correspond to number of placeholdersFormat-string method {2} called with format string "{3}" wants {4} arguments but is given {5} in {1}
@@ -6089,9 +7254,84 @@ but the number of arguments passed does not match with the number of
author intended.
]]>
-
+
+
+
+ MessageFormat supplied where printf style format expected
+ {2} needs printf-style format but called with MessageFormat
+
+
+A method is called that expects a Java printf format string and a list of arguments.
+However, the format string doesn't contain any format specifiers (e.g., %s) but
+does contain message format elements (e.g., {0}). It is likely
+that the code is supplying a MessageFormat string when a printf-style format string
+is required. At runtime, all of the arguments will be ignored
+and the format string will be returned exactly as provided without any formatting.
+
+]]>
+
+
+
+ More arguments are passed than are actually used in the format string
+ Format-string method {2} called with format string "{3}" wants {4} arguments but is given {5} in {1}
+
+
+A format-string method with a variable number of arguments is called,
+but more arguments are passed than are actually used by the format string.
+This won't cause a runtime exception, but the code may be silently omitting
+information that was intended to be included in the formatted string.
+
+]]>
+
+
+
+ Illegal format string
+ Illegal format string "{3}" in {1}
+
+
+The format string is syntactically invalid,
+and a runtime exception will occur when
+this statement is executed.
+
+]]>
+
+
+
+ Format string references missing argument
+ Format string "{3}" needs argument {5} but only {6} are provided in {1}
+
+
+Not enough arguments are passed to satisfy a placeholder in the format string.
+A runtime exception will occur when
+this statement is executed.
+
+]]>
+
+
+
+ Format string placeholder incompatible with passed argument
+ The placeholder {4} is incompatible with
+corresponding argument in {1}
+
+
+The format string placeholder is incompatible with the corresponding
+argument. For example,
+
+ System.out.println("%d\n", "hello");
+
+
The %d placeholder requires a numeric argument, but a string value is
+passed instead.
+A runtime exception will occur when
+this statement is executed.
+
+]]>
+
-
Primitive array passed to function expecting a variable number of object arguments{2} passed to varargs method {3} in {1}
@@ -6117,7 +7357,6 @@ false if o is not the same type as this.
]]>
-
Questionable cast to abstract collection Questionable cast from Collection to abstract class {3} in {1}
@@ -6133,9 +7372,6 @@ to iterate through a collection, you don't need to cast it to a Set or List.
]]>
-
-
-
Impossible cast involving primitive arrayImpossible cast involving primitive array in {1}
@@ -6147,7 +7383,6 @@ This cast will always throw a ClassCastException.
]]>
-
Impossible castImpossible cast from {2} to {3} in {1}
@@ -6155,11 +7390,59 @@ This cast will always throw a ClassCastException.
This cast will always throw a ClassCastException.
+FindBugs tracks type information from instanceof checks,
+and also uses more precise information about the types
+of values returned from methods and loaded from fields.
+Thus, it may have more precise information that just
+the declared type of a variable, and can use this to determine
+that a cast will always throw an exception at runtime.
+
+
+]]>
+
+
+
+ Impossible downcast
+ Impossible downcast from {2} to {3} in {1}
+
+
+This cast will always throw a ClassCastException.
+The analysis believes it knows
+the precise type of the value being cast, and the attempt to
+downcast it to a subtype will always fail by throwing a ClassCastException.
+
+]]>
+
+
+
+ Impossible downcast of toArray() result
+ Impossible downcast of toArray() result to {3} in {1}
+
+
+This code is casting the result of calling toArray() on a collection
+to a type more specific than Object[], as in:
+
This will usually fail by throwing a ClassCastException. The toArray()
+of almost all collections return an Object[]. They can't really do anything else,
+since the Collection object has no reference to the declared generic type of the collection.
+
The correct way to do get an array of a specific type from a collection is to use
+ c.toArray(new String[]);
+ or c.toArray(new String[c.size()]); (the latter is slightly more efficient).
+
There is one common/known exception exception to this. The toArray()
+method of lists returned by Arrays.asList(...) will return a covariantly
+typed array. For example, Arrays.asArray(new String[] { "a" }).toArray()
+will return a String []. FindBugs attempts to detect and suppress
+such cases, but may miss some.
]]>
-
A known null value is checked to see if it is an instance of a typeA known null value is checked to see if it is an instance of {2} in {1}
@@ -6173,7 +7456,8 @@ an indication of some misunderstanding or some other logic error.
]]>
-
+
+
A known null value is checked to see if it is an instance of a typeA known null value is checked to see if it is an instance of {2} in {1}
@@ -6186,7 +7470,6 @@ an indication of some misunderstanding or some other logic error.
]]>
-
instanceof will always return falseinstanceof will always return false in {1}, since a {2} can't be a {3}
@@ -6199,23 +7482,21 @@ an indication of some misunderstanding or some other logic error.
]]>
-
-
instanceof will always return true
- instanceof will always return true in {1}, since all {2} are instances of {3}
+ instanceof will always return true for all non-null values in {1}, since all {2} are instances of {3}
-This instanceof test will always return true. Although this is safe, make sure it isn't
+This instanceof test will always return true (unless the value being tested is null).
+Although this is safe, make sure it isn't
an indication of some misunderstanding or some other logic error.
+If you really want to test the value for being null, perhaps it would be clearer to do
+better to do a null test rather than an instanceof test.
]]>
-
-
-
Unchecked/unconfirmed castUnchecked/unconfirmed cast from {2} to {3} in {1}
@@ -6223,7 +7504,21 @@ an indication of some misunderstanding or some other logic error.
This cast is unchecked, and not all instances of the type casted from can be cast to
-the type it is being cast to. Ensure that your program logic ensures that this
+the type it is being cast to. Check that your program logic ensures that this
+cast will not fail.
+
+]]>
+
+
+
+ Unchecked/unconfirmed cast of return value from method
+ Unchecked/unconfirmed cast from {2} to {3} of return value in {1}
+
+
+This code performs an unchecked cast of the return value of a method.
+The code might be calling the method in such a way that the cast is guaranteed to be
+safe, but FindBugs is unable to verify that the cast is safe. Check that your program logic ensures that this
cast will not fail.
]]>
@@ -6245,18 +7540,19 @@ collection class.
]]>
-
- "." used for regular expression
- "." used for regular expression in {1}
+ "." or "|" used for regular expression
+ "." or "|" used for regular expression in {1}
-A String function is being invoked and "." is being passed
+A String function is being invoked and "." or "|" is being passed
to a parameter that takes a regular expression as an argument. Is this what you intended?
For example
-s.replaceAll(".", "/") will return a String in which every
-character has been replaced by a / character.
+
s.replaceAll(".", "/") will return a String in which every character has been replaced by a '/' character
+
s.split(".") always returns a zero length array of String
+
"ab|cd".replaceAll("|", "/") will return "/a/b/|/c/d/"
+
"ab|cd".split("|") will return array with six (!) elements: [, a, b, |, c, d]
]]>
@@ -6280,20 +7576,17 @@ executed.
-The code here uses File.separator
+The code here uses File.separator
where a regular expression is required. This will fail on Windows
-platforms, where the File.separator is a backslash, which is interpreted in a
+platforms, where the File.separator is a backslash, which is interpreted in a
regular expression as an escape character. Amoung other options, you can just use
-File.separatorChar=='\\' & "\\\\" : File.separator instead of
+File.separatorChar=='\\' ? "\\\\" : File.separator instead of
File.separator
]]>
-
-
-
Overwritten incrementOverwritten increment in {1}
@@ -6318,20 +7611,34 @@ cast to a short or byte, which discards the upper bits of the result.
Since the upper bits are discarded, there may be no difference between
a signed and unsigned right shift (depending upon the size of the shift).
+]]>
+
+
+
+ Possible bad parsing of shift operation
+ Possible bad parsing of shift operation in {1}
+
+
+The code performs an operation like (x << 8 + y). Although this might be correct, probably it was meant
+to perform (x << 8) + y, but shift operation has
+a lower precedence, so it's actually parsed as x << (8 + y).
+
]]>
- Integer shift by an amount not in the range 0..31
- Integer shift by {2} in {1}
+ 32 bit int shifted by an amount not in the range -31..31
+ 32 bit int shifted by {2} bits in {1}
-The code performs an integer shift by a constant amount outside
-the range 0..31.
+The code performs shift of a 32 bit int by a constant amount outside
+the range -31..31.
The effect of this is to use the lower 5 bits of the integer
-value to decide how much to shift by. This probably isn't want was expected,
-and it at least confusing.
+value to decide how much to shift by (e.g., shifting by 40 bits is the same as shifting by 8 bits,
+and shifting by 32 bits is the same as shifting by zero bits). This probably isn't what was expected,
+and it is at least confusing.
]]>
@@ -6349,11 +7656,25 @@ i % 60 * 1000 is (i % 60) * 1000, not i % (60 * 1000).
]]>
+
+ Invocation of hashCode on an array
+ Invocation of hashCode on array in {1}
+
+
+The code invokes hashCode on an array. Calling hashCode on
+an array returns the same value as System.identityHashCode, and ingores
+the contents and length of the array. If you need a hashCode that
+depends on the contents of an array a,
+use java.util.Arrays.hashCode(a).
-
+
+]]>
+
+ Invocation of toString on an array
- Invocation of toString on {2} in {1}
+ Invocation of toString on {2.givenClass} in {1}
@@ -6364,10 +7685,9 @@ String that gives the contents of the array. See Programming Puzzlers, chapter 3
]]>
-
- Invocation of toString on an array
- Invocation of toString on an array in {1}
+ Invocation of toString on an unnamed array
+ Invocation of toString on an unnamed array in {1}
@@ -6378,8 +7698,6 @@ String that gives the contents of the array. See Programming Puzzlers, chapter 3
]]>
-
-
Computation of average could overflowComputation of average could overflow in {1}
@@ -6388,7 +7706,7 @@ String that gives the contents of the array. See Programming Puzzlers, chapter 3
The code computes the average of two integers using either division or signed right shift,
and then uses the result as the index of an array.
If the values being averaged are very large, this can overflow (resulting in the computation
-of a negative average). Assuming that the result is intended to be nonnegative, you
+of a negative average). Assuming that the result is intended to be nonnegative, you
can use an unsigned right shift instead. In other words, rather that using (low+high)/2,
use (low+high) >>> 1
@@ -6401,9 +7719,6 @@ publicized the bug pattern.
]]>
-
-
-
Check for oddness that won't work for negative numbers Check for oddness that won't work for negative numbers in {1}
@@ -6417,9 +7732,6 @@ for oddness, consider using x & 1 == 1, or x % 2 != 0.
]]>
-
-
-
Code contains a hard coded reference to an absolute pathnameHard coded reference to an absolute pathname in {1}
@@ -6433,7 +7745,7 @@ for oddness, consider using x & 1 == 1, or x % 2 != 0.
Bad constant value for month
- {1} passes a bad month value of {2} to {3}
+ Bad month value of {2} passed to {3} in {1}
@@ -6456,7 +7768,7 @@ This code invokes substring(0) on a String, which returns the original value.
hasNext method invokes next
- {1} invokes {3}
+ {1} invokes {2.givenClass}
@@ -6467,11 +7779,10 @@ and the next method is supposed to change the state of the iterator.
]]>
-
- Method calls Thread.sleep() with a lock held
- {1} calls Thread.sleep() with a lock held
-
+ Method calls Thread.sleep() with a lock held
+ {1} calls Thread.sleep() with a lock held
+
This method calls Thread.sleep() with a lock held. This may result
@@ -6483,36 +7794,34 @@ and the next method is supposed to change the state of the iterator.
]]>
-
- Method uses the same code for two branches
- Method {1} uses the same code for two branches
-
+ Method uses the same code for two branches
+ {1} uses the same code for two branches
+
This method uses the same code to implement two branches of a conditional branch.
- Check to ensure that this isn't a coding mistake.
+ Check to ensure that this isn't a coding mistake.
]]>
- Method uses the same code for two switch clauses
- Method {1} uses the same code for two switch clauses
-
+ Method uses the same code for two switch clauses
+ {1} uses the same code for two switch clauses
+
This method uses the same code to implement two clauses of a switch statement.
- This could be a case of duplicate code, but it might also indicate
- a coding mistake.
+ This could be a case of duplicate code, but it might also indicate
+ a coding mistake.
]]>
-
Method accesses a private member variable of owning class
- Method {1} accesses to a private member variable of owning class
+ {1} accesses to a private member variable of owning class
@@ -6524,10 +7833,9 @@ and the next method is supposed to change the state of the iterator.
]]>
-
Method directly allocates a specific implementation of xml interfaces
- Method {1} directly allocates a specific implementation of xml interfaces
+ {1} directly allocates a specific implementation of xml interfaces
@@ -6545,10 +7853,9 @@ and the next method is supposed to change the state of the iterator.
]]>
-
Method superfluously delegates to parent class method
- Method {1} superfluously delegates to parent class method
+ {1} superfluously delegates to parent class method
@@ -6558,21 +7865,19 @@ and the next method is supposed to change the state of the iterator.
]]>
-
Abstract Method is already defined in implemented interfaceAbstract Method {1} is already defined in implemented interface
- This abstract method is already defined in an interface that is implemented by this abstract
+ This abstract method is already defined in an interface that is implemented by this abstract
class. This method can be removed, as it provides no additional value.
]]>
-
-
+ Class is final but declares protected fieldClass {0} is final but declares protected field {1}
@@ -6586,15 +7891,14 @@ and the next method is supposed to change the state of the iterator.
]]>
-
Method assigns boolean literal in boolean expression
- Method {1} assigns boolean literal in boolean expression
+ {1} assigns boolean literal in boolean expression
This method assigns a literal boolean value (true or false) to a boolean variable inside
- an if or while expression. Most probably this was supposed to be a boolean comparison using
+ an if or while expression. Most probably this was supposed to be a boolean comparison using
==, not an assignment using =.
]]>
@@ -6607,32 +7911,134 @@ and the next method is supposed to change the state of the iterator.
This class makes a reference to a class or method that can not be
- resolved using against the libraries it is being analyzed with.
+ resolved using against the libraries it is being analyzed with.
]]>
-
+
+ Unchecked type in generic call
+ Unchecked argument of type Object provided where type {3.givenClass} is expected in {1}
+
+ This call to a generic collection method passes an argument
+ while compile type Object where a specific type from
+ the generic type parameters is expected.
+ Thus, neither the standard Java type system nor static analysis
+ can provide useful information on whether the
+ object being passed as a parameter is of an appropriate type.
+
+ ]]>
+
+ No relationship between generic parameter and method argument
- {2} is incompatible with expected argument type {3} in {1}
+ {2.givenClass} is incompatible with expected argument type {3.givenClass} in {1}
+
+ This call to a generic collection method contains an argument
+ with an incompatible class from that of the collection's parameter
+ (i.e., the type of the argument is neither a supertype nor a subtype
+ of the corresponding generic type argument).
+ Therefore, it is unlikely that the collection contains any objects
+ that are equal to the method argument used here.
+ Most likely, the wrong value is being passed to the method.
+
In general, instances of two unrelated classes are not equal.
+ For example, if the Foo and Bar classes
+ are not related by subtyping, then an instance of Foo
+ should not be equal to an instance of Bar.
+ Among other issues, doing so will likely result in an equals method
+ that is not symmetrical. For example, if you define the Foo class
+ so that a Foo can be equal to a String,
+ your equals method isn't symmetrical since a String can only be equal
+ to a String.
+
+
In rare cases, people do define nonsymmetrical equals methods and still manage to make
+ their code work. Although none of the APIs document or guarantee it, it is typically
+ the case that if you check if a Collection<String> contains
+ a Foo, the equals method of argument (e.g., the equals method of the
+ Foo class) used to perform the equality checks.
+
+ ]]>
+
+
+
+ Collections should not contain themselves
+ Collections should not contain themselves in call to {2.givenClass}
+
+ This call to a generic collection's method would only make sense if a collection contained
+itself (e.g., if s.contains(s) were true). This is unlikely to be true and would cause
+problems if it were true (such as the computation of the hash code resulting in infinite recursion).
+It is likely that the wrong value is being passed as a parameter.
+
+ ]]>
+
+
+
+ Vacuous call to collections
+ For any collection c, calling c.{2.name}(c) doesn't make sense
+
+ This call doesn't make sense. For any collection c, calling c.containsAll(c) should
+always be true, and c.retainAll(c) should have no effect.
+
+ ]]>
+
+
+
+ Don't reuse entry objects in iterators
+ {0} is both an Iterator and a Map.Entry
This call to a generic container's method contains an argument
- with a different class type from that of the container's parameter.
- Therefore, it is unlikely that the container contains any objects
- with the same type as the method argument used here.
-
+
The entrySet() method is allowed to return a view of the
+ underlying Map in which an Iterator and Map.Entry. This clever
+ idea was used in several Map implementations, but introduces the possibility
+ of nasty coding mistakes. If a map m returns
+ such an iterator for an entrySet, then
+ c.addAll(m.entrySet()) will go badly wrong. All of
+ the Map implementations in OpenJDK 1.7 have been rewritten to avoid this,
+ you should to.
+
+ ]]>
+
+
+
+ Adding elements of an entry set may fail due to reuse of Entry objects
+ Adding elements of an entry set may fail due to reuse of {2.simpleClass}.Entry object in {1}
+
+ The entrySet() method is allowed to return a view of the
+ underlying Map in which a single Entry object is reused and returned
+ during the iteration. As of Java 1.6, both IdentityHashMap
+ and EnumMap did so. When iterating through such a Map,
+ the Entry value is only valid until you advance to the next iteration.
+ If, for example, you try to pass such an entrySet to an addAll method,
+ things will go badly wrong.
+
]]>
-
-Static Calendar
-Found static field of type java.util.Calendar in {1}
-
+
+ Don't use removeAll to clear a collection
+ removeAll used to clear a collection in {1}
+
+ If you want to remove all elements from a collection c, use c.clear,
+not c.removeAll(c). Calling c.removeAll(c) to clear a collection
+is less clear, susceptible to errors from typos, less efficient and
+for some collections, might throw a ConcurrentModificationException.
+
+ ]]>
+
+
+
+ Static Calendar field
+ {1} is static field of type java.util.Calendar, which isn't thread safe
+
Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use.
+
Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use.
Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the
application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see
random ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions in sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate().
@@ -6642,29 +8048,26 @@ random ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions in sun.util
and Sun Bug #6178997.
]]>
-
-
-
-Call to static Calendar
-Call to method of static java.util.Calendar in {1}
-
+
+
+ Call to static Calendar
+ Call to method of static java.util.Calendar in {1}
+
Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use.
+
Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use.
The detector has found a call to an instance of Calendar that has been obtained via a static
field. This looks suspicous.
]]>
-
-
-
-
-Static DateFormat
-Found static field of type java.text.DateFormat in {1}
-
+
+
+ Static DateFormat
+ {1} is a static field of type java.text.DateFormat, which isn't thread safe
+
As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use.
+
As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use.
Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the
application.
You may also experience serialization problems.
@@ -6673,25 +8076,57 @@ application.
and Sun Bug #6178997.
]]>
-
-
-
-Call to static DateFormat
-Call to method of static java.text.DateFormat in {1}
-
+
+
+ Call to static DateFormat
+ Call to method of static java.text.DateFormat in {1}
+
As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use.
+
As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use.
The detector has found a call to an instance of DateFormat that has been obtained via a static
field. This looks suspicous.
]]>
-
+
+
+ Comparing values with incompatible type qualifiers
+ Value annotated as having the type qualifier {2.simpleName} is compared for equality with a value that never has that qualifier
+
+
+ A value specified as carrying a type qualifier annotation is
+ compared with a value that doesn't ever carry that qualifier.
+
+
+
+ More precisely, a value annotated with a type qualifier specifying when=ALWAYS
+ is compared with a value that where the same type qualifier specifies when=NEVER.
+
+
+
+ For example, say that @NonNegative is a nickname for
+ the type qualifier annotation @Negative(when=When.NEVER).
+ The following code will generate this warning because
+ the return statement requires a @NonNegative value,
+ but receives one that is marked as @Negative.
+
+ ]]>
+
+
+
Value annotated as carrying a type qualifier used where a value that must not carry that qualifier is required
- Value annotated as carrying type qualifier @{2.excludingPackage} used where a value that must not carry that qualifier is required
+ Value annotated as carrying type qualifier {2.simpleName} used where a value that must not carry that qualifier is required
@@ -6699,18 +8134,18 @@ and Sun Bug
consumed in a location or locations requiring that the value not
carry that annotation.
-
+
+
+
+ Value without a type qualifier used where a value is required to have that qualifier
+ Value without a type qualifier is used in a place that requires a {2.simpleName} annotation
+
+
+ A value is being used in a way that requires the value be annotation with a type qualifier.
+ The type qualifier is strict, so the tool rejects any values that do not have
+ the appropriate annotation.
+
+
+
+ To coerce a value to have a strict annotation, define an identity function where the return value is annotated
+ with the strict annotation.
+ This is the only way to turn a non-annotated value into a value with a strict type qualifier annotation.
+
+
+ ]]>
+
+ Value annotated as never carrying a type qualifier used where value carrying that qualifier is required
- Value annotated as never carrying type qualifier @{2.excludingPackage} used where value carrying that qualifier is required
+ Value annotated as never carrying type qualifier {2.simpleName} used where value carrying that qualifier is required
@@ -6733,7 +8189,7 @@ public @NonNegative Integer example(@Negative Integer value) {
to be consumed in a location or locations requiring that the value does
carry that annotation.
-
+
More precisely, a value annotated with a type qualifier specifying when=NEVER
is guaranteed to reach a use or uses where the same type qualifier specifies when=ALWAYS.
@@ -6741,52 +8197,62 @@ public @NonNegative Integer example(@Negative Integer value) {
TODO: example
-
+
]]>
-
+
+
+
+
- Value that might not carry a type qualifier reaches a use requiring that type qualifier
- Value that might not carry the @{2.excludingPackage} annotation reaches a use requiring that annotation
+ Value that might not carry a type qualifier is always used in a way requires that type qualifier
+ Value that might not carry the {2.simpleName} annotation is always used in a way that requires that type qualifier
- A value that might not carry a type qualifier annotation
- reaches a use which requires that annotation.
+ A value that is annotated as possibility not being an instance of
+ the values denoted by the type qualifier, and the value is guaranteed to be used
+ in a way that requires values denoted by that type qualifier.
-
+ ]]>
+
+
+
+ Value that might carry a type qualifier is always used in a way prohibits it from having that type qualifier
+ Value that might carry the {2.simpleName} annotation is always used in a way that prohibits it from having that type qualifier
+
+
- For example, consider the following method:
+ A value that is annotated as possibility being an instance of
+ the values denoted by the type qualifier, and the value is guaranteed to be used
+ in a way that prohibits values denoted by that type qualifier.
-
+ ]]>
+
+
+
+ Value required to not have type qualifier, but marked as unknown
+ Value is required never be {2.simpleName}, but is explicitly annotated as unknown with regards to {2.simpleName}
+
+
- The mustReturnUntainted method is required to
- return a value carrying the @Untainted annotation,
- but a value not known to carry that annotation is returned.
+ A value is used in a way that requires it to be never be a value denoted by a type qualifier, but
+ there is an explicit annotation stating that it is not known where the value is prohibited from having that type qualifier.
+ Either the usage or the annotation is incorrect.
]]>
-
-
- Unknown value reaches a use which forbids values carrying type qualifier annotation
- Unknown value reaches a use which forbids values carrying the @{2.excludingPackage} annotation
+
+ Value required to have type qualifier, but marked as unknown
+ Value is required to always be {2.simpleName}, but is explicitly annotated as unknown with regards to {2.simpleName}
- A value which might carry a type qualifier annotation reaches
- a use which forbids values carrying that annotation.
-
-
-
- TODO: example.
+ A value is used in a way that requires it to be always be a value denoted by a type qualifier, but
+ there is an explicit annotation stating that it is not known where the value is required to have that type qualifier.
+ Either the usage or the annotation is incorrect.
]]>
@@ -6797,15 +8263,15 @@ public @Untainted Object mustReturnUntainted(Object unknown) {
- This code opens a file in append mode and then wraps the result in an object output stream.
+ This code opens a file in append mode and then wraps the result in an object output stream.
This won't allow you to append to an existing object output stream stored in a file. If you want to be
able to append to an object output stream, you need to keep the object output stream open.
The only situation in which opening a file in append mode and the writing an object output stream
could work is if on reading the file you plan to open it in random access mode and seek to the byte offset
where the append started.
-
-
+
+
TODO: example.
@@ -6813,14 +8279,14 @@ public @Untainted Object mustReturnUntainted(Object unknown) {
- Sychronization on getClass rather than class literal
- Sychronization on getClass rather than class literal in {1}
+ Synchronization on getClass rather than class literal
+ Synchronization on getClass rather than class literal in {1}
This instance method synchronizes on this.getClass(). If this class is subclassed,
subclasses will synchronize on the class object for the subclass, which isn't likely what was intended.
- For example, consider this code from java.awt.Label:
+ For example, consider this code from java.awt.Label:
private static final String base = "label";
private static int nameCounter = 0;
@@ -6829,9 +8295,9 @@ public @Untainted Object mustReturnUntainted(Object unknown) {
return base + nameCounter++;
}
}
-
+
Subclasses of Label won't synchronize on the same subclass, giving rise to a datarace.
- Instead, this code should be synchronizing on Label.class
+ Instead, this code should be synchronizing on Label.class
private static final String base = "label";
private static int nameCounter = 0;
@@ -6840,90 +8306,336 @@ public @Untainted Object mustReturnUntainted(Object unknown) {
return base + nameCounter++;
}
}
-
+
Bug pattern contributed by Jason Mehrens
]]>
-
+
+ Method may fail to clean up stream or resource
+ {1} may fail to clean up {2}
+
+
+ This method may fail to clean up (close, dispose of) a stream,
+ database object, or other
+ resource requiring an explicit cleanup operation.
+
+
+
+ In general, if a method opens a stream or other resource,
+ the method should use a try/finally block to ensure that
+ the stream or resource is cleaned up before the method
+ returns.
+
+
+
+ This bug pattern is essentially the same as the
+ OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE
+ bug patterns, but is based on a different
+ (and hopefully better) static analysis technique.
+ We are interested is getting feedback about the
+ usefulness of this bug pattern.
+ To send feedback, either:
+
+ In particular,
+ the false-positive suppression heuristics for this
+ bug pattern have not been extensively tuned, so
+ reports about false positives are helpful to us.
+
+
+
+ See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for
+ a description of the analysis technique.
+
+ ]]>
+
+
+
+
+
+
+
+ Method may fail to clean up stream or resource on checked exception
+ {1} may fail to clean up {2} on checked exception
+
+
+ This method may fail to clean up (close, dispose of) a stream,
+ database object, or other
+ resource requiring an explicit cleanup operation.
+
+
+
+ In general, if a method opens a stream or other resource,
+ the method should use a try/finally block to ensure that
+ the stream or resource is cleaned up before the method
+ returns.
+
+
+
+ This bug pattern is essentially the same as the
+ OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE
+ bug patterns, but is based on a different
+ (and hopefully better) static analysis technique.
+ We are interested is getting feedback about the
+ usefulness of this bug pattern.
+ To send feedback, either:
+
+ In particular,
+ the false-positive suppression heuristics for this
+ bug pattern have not been extensively tuned, so
+ reports about false positives are helpful to us.
+
+
+
+ See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for
+ a description of the analysis technique.
+
+ ]]>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Unexpected/undesired warning from FindBugs
+ Unexpected/undesired {2} FindBugs warning in {1}
+
+ FindBugs generated a warning that, according to a @NoWarning annotated,
+ is unexpected or undesired
+ ]]>
+
+
+
+ Missing expected or desired warning from FindBugs
+ Missing expected or desired {2} FindBugs warning in {1}
+
+ FindBugs didn't generate generated a warning that, according to a @ExpectedWarning annotated,
+ is expected or desired
+ ]]>
+
+
+
+ Return value of putIfAbsent ignored, value passed to putIfAbsent reused
+ Return value of putIfAbsent is ignored, but {4} is reused in {1}
+
+ putIfAbsent method is typically used to ensure that a
+ single value is associated with a given key (the first value for which put
+ if absent succeeds).
+ If you ignore the return value and retain a reference to the value passed in,
+ you run the risk of retaining a value that is not the one that is associated with the key in the map.
+ If it matters which one you use and you use the one that isn't stored in the map,
+ your program will behave incorrectly.
+ ]]>
+
+
+
+ Potential lost logger changes due to weak reference in OpenJDK
+ Changes to logger could be lost in {1}
+
+ OpenJDK introduces a potential incompatibility.
+ In particular, the java.util.logging.Logger behavior has
+ changed. Instead of using strong references, it now uses weak references
+ internally. That's a reasonable change, but unfortunately some code relies on
+ the old behavior - when changing logger configuration, it simply drops the
+ logger reference. That means that the garbage collector is free to reclaim
+ that memory, which means that the logger configuration is lost. For example,
+consider:
+
+
+
public static void initLogging() throws Exception {
+ Logger logger = Logger.getLogger("edu.umd.cs");
+ logger.addHandler(new FileHandler()); // call to change logger configuration
+ logger.setUseParentHandlers(false); // another call to change logger configuration
+}
+
+
The logger reference is lost at the end of the method (it doesn't
+escape the method), so if you have a garbage collection cycle just
+after the call to initLogging, the logger configuration is lost
+(because Logger only keeps weak references).
+
+
public static void main(String[] args) throws Exception {
+ initLogging(); // adds a file handler to the logger
+ System.gc(); // logger configuration lost
+ Logger.getLogger("edu.umd.cs").info("Some message"); // this isn't logged to the file as expected
+}
+
Ulf Ochsenfahrt and Eric Fellheimer
+ ]]>
+
+
+
+ Sequence of calls to concurrent abstraction may not be atomic
+ Sequence of calls to {2} may not be atomic in {1}
+
+ This code contains a sequence of calls to a concurrent abstraction
+ (such as a concurrent hash map).
+ These calls will not be executed atomically.
+ ]]>
+
+
+
+ Reliance on default encoding
+ Found reliance on default encoding in {1}: {2}
+
+ Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.
+]]>
+
+
+
+ Method tightens nullness annotation on parameter
+ Method {1} overrides the nullness annotation relaxing the ancestor method requirements on parameter.
+
+
+ A method should always implement the contract of a method it overrides. Thus, if a method takes a parameter
+ that is marked as @Nullable, you shouldn't override that method in a subclass with a method where that parameter is @Nonnull.
+ Doing so violates the contract that the method should handle a null parameter.
+ ]]>
+
+
+
+ Method tightens nullness annotation on parameter
+ Method {1} overrides the nullness annotation of parameter {2} in an incompatible way
+
+
+ A method should always implement the contract of a method it overrides. Thus, if a method takes a parameter
+ that is marked as @Nullable, you shouldn't override that method in a subclass with a method where that parameter is @Nonnull.
+ Doing so violates the contract that the method should handle a null parameter.
+ ]]>
+
+
+
+
+ Method relaxes nullness annotation on return value
+ Method {1} overrides the return value nullness annotation in an incompatible way.
+
+
+ A method should always implement the contract of a method it overrides. Thus, if a method takes is annotated
+ as returning a @Nonnull value,
+ you shouldn't override that method in a subclass with a method annotated as returning a @Nullable or @CheckForNull value.
+ Doing so violates the contract that the method shouldn't return null.
+ ]]>
+
+
-
- Infinite Loop
- Use of volatile
- Unsafe inheritance
- Use of floating point precision
- Testing prototype and incomplete bug pattern
- Dubious catching of IllegalMonitorStateException
- Bad implementation of cloneable idiom
- Possible atomicity violation
- Incorrect use of finalizers
- Checking String equality using == or !=
- Synchronization on updated field (Mutable Lock)
- Unsynchronized get method, synchronized set method
- Input/Output problem
- Initialization circularity
- Suspicious static initializer
- Inconsistent synchronization
- Problems with equals()
- Problems with compareTo()
- Equal objects must have equal hashcodes
- API misuse
- Dubious method used
- Questionable Boxing of primitive value
- Uninitialized read of field in constructor
- Method ignores results of InputStream.read()
- Naked notify
- Unconditional wait
- Method spins on field
- Possible double check of field
- Wait not in loop
- Using notify() rather than notifyAll()
- Dropped or ignored exception
- Method invokes run()
- Incorrect definition of Iterator
- Serializable class with no Version ID
- Incorrect definition of Serializable class
- Class's writeObject() method is synchronized but nothing else is
- Class's readObject() method is synchronized
- Constructor invokes Thread.start()
- Mutable static field
- Method returning array may expose internal representation
- Confusing method name
- Unread field should be static
- Unused field
- Unread field
- Unwritten field
- Inner class could be made static
- Wait with two locks held
- Bad use of return value from method
- Ambiguous invocation
- Huge String constants
- HTTP Response splitting vunerability
- Cross site scripting vunerabilitity
- Null pointer dereference
+ Format string problem
+ Analysis skipped
+ Infinite Loop
+ Use of volatile
+ Unsafe inheritance
+ Use of floating point precision
+ Testing prototype and incomplete bug pattern
+ Dubious catching of IllegalMonitorStateException
+ Bad implementation of cloneable idiom
+ Covariant array assignment
+ Possible atomicity violation
+ Incorrect use of finalizers
+ Checking String equality using == or !=
+ Synchronization on updated field (Mutable Lock)
+ Unsynchronized get method, synchronized set method
+ Input/Output problem
+ Initialization circularity
+ Suspicious static initializer
+ Mutable servlet field
+ Inconsistent synchronization
+ Problems with implementation of equals()
+ Problems with implementation of compareTo()
+ Equal objects must have equal hashcodes
+ API misuse
+ Dubious method used
+ Questionable Boxing of primitive value
+ Uninitialized read of field in constructor
+ Method ignores results of InputStream.read()
+ Naked notify
+ Unconditional wait
+ Method spins on field
+ Double check pattern
+ Wait not in loop
+ Using notify() rather than notifyAll()
+ Dropped or ignored exception
+ Method invokes run()
+ Incorrect definition of Iterator
+ Serializable class with no Version ID
+ Incorrect definition of Serializable class
+ Class's writeObject() method is synchronized but nothing else is
+ Class's readObject() method is synchronized
+ Constructor invokes Thread.start()
+ Mutable static field
+ Mutable enum field
+ Method returning array may expose internal representation
+ Confusing method name
+ Unread field should be static
+ Unused field
+ Unread field
+ Unwritten field
+ Inner class could be made static
+ Wait with two locks held
+ Range checks
+ Bad use of return value from method
+ Logger problem
+ Ambiguous invocation
+ Huge String constants
+ HTTP Response splitting vulnerability
+ Path traversal
+ Cross site scripting vulnerability
+ Null pointer dereference
+ Bogus random warning
+ Repeated conditional testStream not closed on all paths
- Prefer zero length arrays to null to indicate no results
+ Prefer zero length arrays to null to indicate no resultsUseless control flowRedundant comparison to nullLock not released on all paths
- Suspicious reference comparison
- Suspicious equals() comparison
+ Questionable use of reference equality rather than calling equals
+ Comparing incompatible types for equalityMismatched wait() or notify()Useless self-operationSuspicious integer expressionSuspicious bitwise logical expressionUnsynchronized Lazy Initialization
- Synchronization on JSR166 Lock
+ Synchronization on java.util.concurrent objectsPrivate method is never calledUncallable method of anonymous classStoring reference to mutable objectSuspicious use of non-short-circuit boolean operatorDatabase resource not closed on all pathsString concatenation in loop using + operator
+ Inefficient code which can be moved outside of the loop
+ Inefficient use of String.indexOf(String) or String.lastIndexOf(String)Inefficient use of collection.toArray(new Foo[0])Swing coding rulesImproperly implemented JUnit TestCase
@@ -6941,14 +8653,16 @@ public @Untainted Object mustReturnUntainted(Object unknown) {
RuntimeException captureTest for floating point equalityUnnecessary Math on constants
+ Useless code
+ Rough value of known constantCircular DependenciesRedundant InterfacesMultithreaded Instance AccessPublic Semaphores
+ Bad shiftCasting from integer valuesRegular expressions
- SQL Problem
- Potential deadlock or unexpected blocking
+ Potential SQL ProblemPossible locking on wrong objectEmpty Synchronized blocksQuestionable for loops
@@ -6957,6 +8671,7 @@ public @Untainted Object mustReturnUntainted(Object unknown) {
Questionable integer mathMisuse of static fieldsViolation of net.jcip annotations
+ Useless/non-informative string generatedDubious method invocationWarning inspired by Josh Bloch's and Neal Gafter's Programming PuzzlersSleep with lock held
@@ -6969,10 +8684,10 @@ public @Untainted Object mustReturnUntainted(Object unknown) {
Questionable Boolean AssignmentVersion compatibility issueUse doPrivileged
- Suspicious calls to generic container methods
+ Suspicious calls to generic collection methodsStatic use of type Calendar or DateFormatInconsistent use of type qualifier annotations
-
-
-
-
+ Unsatisfied obligation to clean up stream or resource
+ FindBugs did not produce the expected warnings on a method
+ Unintended contention or possible deadlock due to locking on shared objects
+
diff --git a/src/test/java/hudson/plugins/violations/ReportedFileAsserter.java b/src/test/java/hudson/plugins/violations/ReportedFileAsserter.java
new file mode 100644
index 0000000..77b33b7
--- /dev/null
+++ b/src/test/java/hudson/plugins/violations/ReportedFileAsserter.java
@@ -0,0 +1,94 @@
+package hudson.plugins.violations;
+
+import static com.google.common.base.Joiner.on;
+import static com.google.common.collect.Lists.newArrayList;
+import static com.google.common.collect.Lists.transform;
+import static com.google.common.collect.Maps.uniqueIndex;
+import static org.junit.Assert.fail;
+import hudson.plugins.violations.model.BuildModel.FileCount;
+import hudson.plugins.violations.model.Violation;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableMap;
+
+public class ReportedFileAsserter {
+
+ private ViolationsReportAsserter violationsReportAsserter;
+ private String reportedFile;
+
+ public ReportedFileAsserter(
+ ViolationsReportAsserter violationsReportAsserter,
+ String reportedFile) {
+ this.violationsReportAsserter = violationsReportAsserter;
+ this.reportedFile = reportedFile;
+ }
+
+ public ReportedFileAsserter wasReported() {
+ getOrFail();
+ return this;
+ }
+
+ private FileCount getOrFail() {
+ Set fileCounts = violationsReportAsserter
+ .getViolationsReport().getModel().getTypeMap()
+ .get(violationsReportAsserter.getTypeDescriptor().getName());
+ ImmutableMap nameToFileCount = nameToFileCount(fileCounts);
+ if (nameToFileCount.containsKey(reportedFile))
+ return nameToFileCount.get(reportedFile);
+ fail("Could not find \"" + reportedFile + "\" in:\n"
+ + on('\n').join(nameToFileCount.keySet()));
+ return null;
+
+ }
+
+ public ReportedFileAsserter reportedViolation(int line, String source,
+ String message) {
+ for (Violation v : getViolations())
+ if (v.getLine() == line && v.getSource().equals(source)
+ && v.getMessage().equals(message))
+ return this;
+ fail("Could not find message \"" + message + "\" at " + line
+ + " Found:\n"
+ + Joiner.on('\n').join(readableStrings(getViolations())));
+ return this;
+ }
+
+ private Iterable readableStrings(List violations) {
+ return transform(violations, new Function() {
+ @Override
+ public String apply(Violation input) {
+ return input.getLine() + " " + input.getSource() + " "
+ + input.getMessage();
+ }
+ });
+ }
+
+ private List getViolations() {
+ List violations = newArrayList();
+ Map> lineMap = getOrFail().getFileModel()
+ .getLineViolationMap();
+ for (Integer line : lineMap.keySet())
+ for (Violation violation : lineMap.get(line))
+ violations.add(violation);
+ return violations;
+ }
+
+ private ImmutableMap nameToFileCount(
+ Set fileCounts) {
+ return uniqueIndex(fileCounts, new Function() {
+ @Override
+ public String apply(FileCount input) {
+ return input.getName();
+ }
+ });
+ }
+
+ public ViolationsReportAsserter and() {
+ return violationsReportAsserter;
+ }
+}
diff --git a/src/test/java/hudson/plugins/violations/ViolationsParserTest.java b/src/test/java/hudson/plugins/violations/ViolationsParserTest.java
index d4c5ec2..d8e3a30 100644
--- a/src/test/java/hudson/plugins/violations/ViolationsParserTest.java
+++ b/src/test/java/hudson/plugins/violations/ViolationsParserTest.java
@@ -8,21 +8,23 @@
import java.net.URL;
public abstract class ViolationsParserTest {
-
- protected abstract FullBuildModel getFullBuildModel(String filename) throws IOException;
-
- protected FullBuildModel getFullBuildModel(ViolationsParser parser, String filename) throws IOException {
- URL url = getClass().getResource(filename);
+
+ protected abstract FullBuildModel getFullBuildModel(String filename)
+ throws IOException;
+
+ protected FullBuildModel getFullBuildModel(ViolationsParser parser,
+ String filename) throws IOException {
+ URL url = getClass().getResource(filename);
File xmlFile;
try {
xmlFile = new File(url.toURI());
- } catch(URISyntaxException e) {
+ } catch (URISyntaxException e) {
xmlFile = new File(url.getPath());
}
-
+
FullBuildModel model = new FullBuildModel();
parser.parse(model, xmlFile.getParentFile(), xmlFile.getName(), null);
model.cleanup();
return model;
- }
+ }
}
diff --git a/src/test/java/hudson/plugins/violations/ViolationsReportAsserter.java b/src/test/java/hudson/plugins/violations/ViolationsReportAsserter.java
new file mode 100644
index 0000000..ae7d5fd
--- /dev/null
+++ b/src/test/java/hudson/plugins/violations/ViolationsReportAsserter.java
@@ -0,0 +1,29 @@
+package hudson.plugins.violations;
+
+public class ViolationsReportAsserter {
+ private ViolationsReport violationsReport;
+ private TypeDescriptor typeDescriptor;
+
+ public ViolationsReportAsserter(ViolationsReport violationsReport,
+ TypeDescriptor typeDescriptor) {
+ this.violationsReport = violationsReport;
+ this.typeDescriptor = typeDescriptor;
+ }
+
+ public static ViolationsReportAsserter assertThat(
+ ViolationsReport violationsReport, TypeDescriptor typeDescriptor) {
+ return new ViolationsReportAsserter(violationsReport, typeDescriptor);
+ }
+
+ public ReportedFileAsserter assertThat(String reportedFile) {
+ return new ReportedFileAsserter(this, reportedFile);
+ }
+
+ TypeDescriptor getTypeDescriptor() {
+ return typeDescriptor;
+ }
+
+ ViolationsReport getViolationsReport() {
+ return violationsReport;
+ }
+}
diff --git a/src/test/java/hudson/plugins/violations/ViolationsReportBuilder.java b/src/test/java/hudson/plugins/violations/ViolationsReportBuilder.java
new file mode 100644
index 0000000..51f9ece
--- /dev/null
+++ b/src/test/java/hudson/plugins/violations/ViolationsReportBuilder.java
@@ -0,0 +1,69 @@
+package hudson.plugins.violations;
+
+import static hudson.plugins.violations.MagicNames.VIOLATIONS;
+import static hudson.plugins.violations.ViolationsPublisher.createBuildAction;
+import static hudson.plugins.violations.ViolationsReportAsserter.assertThat;
+import static java.lang.Thread.currentThread;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.powermock.api.mockito.PowerMockito.spy;
+import hudson.FilePath;
+import hudson.model.Build;
+import hudson.model.AbstractBuild;
+
+import java.io.File;
+
+import jenkins.model.Jenkins;
+
+import org.powermock.api.mockito.PowerMockito;
+
+public class ViolationsReportBuilder {
+ private String sourcePathPattern;
+ private TypeDescriptor typeDescriptor;
+
+ private ViolationsReportBuilder(TypeDescriptor typeDescriptor) {
+ this.typeDescriptor = typeDescriptor;
+ }
+
+ public static ViolationsReportBuilder violationsReport(
+ TypeDescriptor typeDescriptor) {
+ return new ViolationsReportBuilder(typeDescriptor);
+ }
+
+ public ViolationsReportBuilder reportedIn(String sourcePathPattern) {
+ this.sourcePathPattern = sourcePathPattern;
+ return this;
+ }
+
+ public ViolationsReportAsserter perform() throws Exception {
+ mockJenkins();
+
+ ViolationsConfig config = new ViolationsConfig();
+ config.setSourcePathPattern(sourcePathPattern);
+ TypeConfig typeConfig = new TypeConfig(typeDescriptor.getName());
+ typeConfig.setPattern(sourcePathPattern);
+ config.getTypeConfigs().put(typeDescriptor.getName(), typeConfig);
+
+ FilePath workspace = new FilePath(projectRootDir());
+ FilePath targetPath = new FilePath(new File(projectRootDir().getPath()
+ + "/" + VIOLATIONS));
+ FilePath htmlPath = new FilePath(projectRootDir());
+ AbstractBuild, ?> build = mock(Build.class);
+ when(build.getRootDir()).thenReturn(projectRootDir());
+ ViolationsReport violationsReport = createBuildAction(workspace,
+ targetPath, htmlPath, config, build).getReport();
+ return assertThat(violationsReport, typeDescriptor);
+ }
+
+ private Jenkins mockJenkins() {
+ Jenkins mockedJenkins = mock(Jenkins.class);
+ spy(Jenkins.class);
+ PowerMockito.when(Jenkins.getInstance()).thenReturn(mockedJenkins);
+ return mockedJenkins;
+ }
+
+ private File projectRootDir() {
+ return new File(currentThread().getContextClassLoader()
+ .getResource("rootDir.txt").getPath()).getParentFile();
+ }
+}
diff --git a/src/test/java/hudson/plugins/violations/types/checkstyle/CheckstyleParserTest.java b/src/test/java/hudson/plugins/violations/types/checkstyle/CheckstyleParserTest.java
new file mode 100644
index 0000000..67037f8
--- /dev/null
+++ b/src/test/java/hudson/plugins/violations/types/checkstyle/CheckstyleParserTest.java
@@ -0,0 +1,36 @@
+package hudson.plugins.violations.types.checkstyle;
+
+import static hudson.plugins.violations.ViolationsReportBuilder.violationsReport;
+import static hudson.plugins.violations.types.checkstyle.CheckstyleDescriptor.DESCRIPTOR;
+import jenkins.model.Jenkins;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({ Jenkins.class })
+public class CheckstyleParserTest {
+ @Test
+ public void testThatCheckstyleCanBeParsed() throws Exception {
+ violationsReport(DESCRIPTOR)
+ .reportedIn("**/checkstyle-report.xml")
+ .perform()
+ .assertThat(
+ "path/to/jenkins/workspace/jobname/module/src/main/java/se/bjurr/code/CheckstyleFile.java")
+ .wasReported()
+ .reportedViolation(60, "TrailingCommentCheck",
+ "Checkstyle \"comment\".")
+ .reportedViolation(64, "MemberNameCheck",
+ "Other 'checkstyle' comment.")
+ .and()
+ .assertThat(
+ "path/to/jenkins/workspace/jobname/module/src/main/java/se/bjurr/UnchangedFileInCheckstyle.java")
+ .wasReported()
+ .reportedViolation(
+ 60,
+ "TrailingCommentCheck",
+ "UnchangedFileInCheckstyle comment in checkstyle this one is not changed in PR.");
+ }
+}
diff --git a/src/test/java/hudson/plugins/violations/types/findbugs/FindBugsParserTest.java b/src/test/java/hudson/plugins/violations/types/findbugs/FindBugsParserTest.java
new file mode 100644
index 0000000..951be6a
--- /dev/null
+++ b/src/test/java/hudson/plugins/violations/types/findbugs/FindBugsParserTest.java
@@ -0,0 +1,25 @@
+package hudson.plugins.violations.types.findbugs;
+
+import static hudson.plugins.violations.ViolationsReportBuilder.violationsReport;
+import static hudson.plugins.violations.types.findbugs.FindBugsDescriptor.DESCRIPTOR;
+import jenkins.model.Jenkins;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({ Jenkins.class })
+public class FindBugsParserTest {
+ @Test
+ public void testThatFindBugsFileCanBeParsed() throws Exception {
+ violationsReport(DESCRIPTOR)
+ .reportedIn("**/findbugs-report.xml")
+ .perform()
+ .assertThat("se/bjurr/analyzer/Code.java")
+ .wasReported()
+ .reportedViolation(8, "EQ_ALWAYS_FALSE",
+ "equals method always returns false");
+ }
+}
diff --git a/src/test/java/hudson/plugins/violations/types/pmd/PMDParserTest.java b/src/test/java/hudson/plugins/violations/types/pmd/PMDParserTest.java
new file mode 100644
index 0000000..ad576d8
--- /dev/null
+++ b/src/test/java/hudson/plugins/violations/types/pmd/PMDParserTest.java
@@ -0,0 +1,32 @@
+package hudson.plugins.violations.types.pmd;
+
+import static hudson.plugins.violations.ViolationsReportBuilder.violationsReport;
+import static hudson.plugins.violations.types.pmd.PMDDescriptor.DESCRIPTOR;
+import jenkins.model.Jenkins;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({ Jenkins.class })
+public class PMDParserTest {
+ @Test
+ public void testThatPMDFileCanBeParsed() throws Exception {
+ violationsReport(DESCRIPTOR)
+ .reportedIn("**/pmd-report.xml")
+ .perform()
+ .assertThat(
+ "path/to/jenkins/workspace/jobname/module/src/main/java/se/bjurr/PMDAndCheckstyle.java")
+ .wasReported()
+ .reportedViolation(312, "OverrideBothEqualsAndHashcode",
+ "PMDAndCheckstyle comment in pmd")
+ .and()
+ .assertThat(
+ "path/to/jenkins/workspace/jobname/module/src/main/java/se/bjurr/PMDFile.java")
+ .wasReported()
+ .reportedViolation(312, "OverrideBothEqualsAndHashcode",
+ "PMD file comment");
+ }
+}
diff --git a/src/test/java/hudson/plugins/violations/types/resharper/ReSharperParserTest.java b/src/test/java/hudson/plugins/violations/types/resharper/ReSharperParserTest.java
new file mode 100644
index 0000000..8bbba4f
--- /dev/null
+++ b/src/test/java/hudson/plugins/violations/types/resharper/ReSharperParserTest.java
@@ -0,0 +1,32 @@
+package hudson.plugins.violations.types.resharper;
+
+import static hudson.plugins.violations.ViolationsReportBuilder.violationsReport;
+import static hudson.plugins.violations.types.resharper.ReSharperDescriptor.DESCRIPTOR;
+import jenkins.model.Jenkins;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({ Jenkins.class })
+public class ReSharperParserTest {
+ @Test
+ public void testThatFindBugsFileCanBeParsed() throws Exception {
+ violationsReport(DESCRIPTOR)
+ .reportedIn("**/resharper-report.xml")
+ .perform()
+ .assertThat("MyLibrary/Class1.cs")
+ .wasReported()
+ .reportedViolation(0, "Redundancies in Code",
+ "Using directive is not required by the code and can be safely removed")
+ .reportedViolation(9, "Common Practices and Code Improvements",
+ "Join declaration and assignment")
+ .and()
+ .assertThat("MyLibrary/Properties/AssemblyInfo.cs")
+ .wasReported()
+ .reportedViolation(2, "Redundancies in Code",
+ "Using directive is not required by the code and can be safely removed");
+ }
+}
diff --git a/src/test/resources/hudson/plugins/violations/types/checkstyle/checkstyle-report.xml b/src/test/resources/hudson/plugins/violations/types/checkstyle/checkstyle-report.xml
new file mode 100644
index 0000000..5fcb934
--- /dev/null
+++ b/src/test/resources/hudson/plugins/violations/types/checkstyle/checkstyle-report.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/test/resources/hudson/plugins/violations/types/findbugs/findbugs-report.xml b/src/test/resources/hudson/plugins/violations/types/findbugs/findbugs-report.xml
new file mode 100644
index 0000000..7b60273
--- /dev/null
+++ b/src/test/resources/hudson/plugins/violations/types/findbugs/findbugs-report.xml
@@ -0,0 +1,37 @@
+
+
+
+
+ /home/bjerre/workspace/jenkins-violation-comments-to-stash-plugin/plugin-example/build/classes/main/se/bjurr/analyzer/Code.class
+ /home/bjerre/workspace/jenkins-violation-comments-to-stash-plugin/plugin-example/src/main/java/se/bjurr/analyzer/Code.java
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/test/resources/hudson/plugins/violations/types/pmd/pmd-report.xml b/src/test/resources/hudson/plugins/violations/types/pmd/pmd-report.xml
new file mode 100644
index 0000000..b0b7fe3
--- /dev/null
+++ b/src/test/resources/hudson/plugins/violations/types/pmd/pmd-report.xml
@@ -0,0 +1,35 @@
+
+
+
+
+ PMD file comment
+
+
+
+
+
+ PMDAndCheckstyle comment in pmd
+
+
+
+
+
+ UnchangedInPR comment in pmd, this one is not changed in PR
+
+
+
diff --git a/src/test/resources/hudson/plugins/violations/types/resharper/resharper-report.xml b/src/test/resources/hudson/plugins/violations/types/resharper/resharper-report.xml
new file mode 100644
index 0000000..999c45a
--- /dev/null
+++ b/src/test/resources/hudson/plugins/violations/types/resharper/resharper-report.xml
@@ -0,0 +1,21 @@
+
+
+
+
+ CSharpPlayground.sln
+
+ 9B2650A2-C7C6-435F-80D6-D6C7B522FFF9
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/test/resources/rootDir.txt b/src/test/resources/rootDir.txt
new file mode 100644
index 0000000..00d91f3
--- /dev/null
+++ b/src/test/resources/rootDir.txt
@@ -0,0 +1 @@
+Placeholder to mark project root dir
\ No newline at end of file