etc.messages.xml Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sb-contrib Show documentation
Show all versions of sb-contrib Show documentation
An auxiliary findbugs.sourceforge.net plugin for java bug detectors that fall outside the narrow scope of detectors to be packaged with the product itself.
The newest version!
<?xml version="1.0" encoding="UTF-8"?> <MessageCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="messagecollection.xsd"> <Plugin> <ShortDescription>fb-contrib plugin</ShortDescription> <Details> <![CDATA[ <p>This plugin contains FindBugs detectors from the fb-contrib project</p> ]]> </Details> <BugsUrl>http://fb-contrib.sourceforge.net/bugdescriptions.html</BugsUrl> <AllBugsUrl>http://fb-contrib.sourceforge.net/bugdescriptions.html</AllBugsUrl> </Plugin> <!-- Detectors --> <Detector class="com.mebigfatguy.fbcontrib.collect.CollectStatistics"> <Details> <![CDATA[ <p>Collects statistics for other detectors</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.collect.CollectMethodsReturningImmutableCollections"> <Details> <![CDATA[ <p>Collects method calls that may return immutable collections</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.collect.CollectNullableMethodStatus"> <Details> <![CDATA[ <p>Collects method calls that can return null</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.InefficientStringBuffering"> <Details> <![CDATA[ <p>Looks for appending strings inside of calls to StringBuffer or StringBuilder append.</p> <pre> StringBuilder sb = new StringBuilder(); sb.append(a + b); return sb.toString(); </pre> You should use the .append method to append values <pre> sb.append(a).append(b); </pre> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SyncCollectionIterators"> <Details> <![CDATA[ <p>Looks for use of iterators on synchronized collections built from the java.util.Collections class.</p> <p>As the collection in question was built through Collections.synchronizedXXX, an assumption is made that this collection must be multithreading safe. However, iterator access is used, which is explicitly unsafe. When iterators are to be used, synchronization should be done manually.</p> <p>It is a slow detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CyclomaticComplexity"> <Details> <![CDATA[ <p>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'.</p> <p>It is a slow detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.OverlyConcreteParameter"> <Details> <![CDATA[ <p>Looks for parameters that are defined by classes, but where the method only uses methods defined by an implemented interface or superclass of that class. Relying on concrete classes in public signatures causes cohesion, and makes low impact changes more difficult.</p> <p>It is a slow detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ListIndexedIterating"> <Details> <![CDATA[ <p>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.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnrelatedCollectionContents"> <Details> <![CDATA[ <p>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 adding an instance of that class to the collection, or array.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.RuntimeExceptionDeclared"> <Details> <![CDATA[ <p>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. </p> <p>It is a fast detector.</p> <p>As an example, every method could be declared like this: <code> public void foo() throws NullPointerException { } </code> But what does that tell you? Is this method very very likely to throw NullPointerExceptions? If it is, why isn't this method handling them so that exceptions aren't thrown? So don't do this. If an NPE is very likely, then check for it, and handle the situation. </p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ClassEnvy"> <Details> <![CDATA[ <p>Looks for methods that use a high percentage of methods from another class over their class' 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'.</p> <p>It is a slow detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.LiteralStringComparison"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PartiallyConstructedObjectAccess"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.DubiousListCollection"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ParallelLists"> <Details> <![CDATA[ <p>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 lists are related in key/value fashion, then use a map instead.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.FinalParameters"> <Details> <![CDATA[ <p>Looks for methods that correctly do not write to a parameter. To help document this, you should consider defining these parameters as final.</p> <p>It is a slow detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.AbstractClassEmptyMethods"> <Details> <![CDATA[ <p>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 simply define this method as abstract, so that correct subclass behavior is enforced.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ManualArrayCopy"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.FloatingPointLoops"> <Details> <![CDATA[ <p>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 calculate the correct floating point value from the index.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NonCollectionMethodUse"> <Details> <![CDATA[ <p>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:<br/> <table border="1"> <tr><th>Old Method</th><th>New Method</th></tr> <tr><td>Hashtable.contains</td><td>Map.containsValue</td></tr> <tr><td>Hashtable.elements</td><td>Map.elements</td></tr> <tr><td>Hashtable.keys</td><td>Map.keySet</td></tr> <tr><td>Vector.addElement</td><td>List.add</td></tr> <tr><td>Vector.elementAt</td><td>List.get</td></tr> <tr><td>Vector.insertElementAt</td><td>List.add</td></tr> <tr><td>Vector.removeAllElements</td><td>List.clear</td></tr> <tr><td>Vector.removeElement</td><td>List.remove</td></tr> <tr><td>Vector.removeElementAt</td><td>List.remove</td></tr> <tr><td>Vector.setElementAt</td><td>List.set</td></tr> </table> </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ConfusingAutoboxedOverloading"> <Details> <![CDATA[ <p>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 <pre><code> test('a') </code></pre> would map to <pre><code> public void test(Character c) </code></pre> but it instead maps to one that takes an int, long, float or double, such as <pre><code> public void test(int i) </code></pre> </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.AbnormalFinallyBlockReturn"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.StaticMethodInstanceInvocation"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SpuriousThreadStates"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NeedlessAutoboxing"> <Details> <![CDATA[ <p>Looks for methods that pass a primitive wrapper class object to the same class' Constructor. Patterns found are: <ul> <li>new Boolean(Boolean)</li> <li>new Byte(Byte)</li> <li>new Character(Character)</li> <li>new Short(Short)</li> <li>new Integer(Integer)</li> <li>new Long(Long)</li> <li>new Float(Float)</li> <li>new Double(Double)</li> </ul> Since primitive wrapper classes are immutable this is needless garbage being created. Just use the original reference. </p> <p>It also looks for calls to BoxedClass.valueOf(x) where X is already a BoxedClass</p> <p>It also looks for calls to BoxedClass.valueOf(myString).boxedValue(), when instead it is simpler to use BoxedClass.parseBoxed(myString)</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnnecessaryStoreBeforeReturn"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CopiedOverriddenMethod"> <Details> <![CDATA[ <p>Looks for methods that are direct copies of the implementation in the superclass.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ArrayBasedCollections"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.OrphanedDOMNode"> <Details> <![CDATA[ <p>Looks for methods that create DOM nodes but do not add them to any DOM Document. Either the node needed to be added to the tree, or the node likely was created in error.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.AbstractOverriddenMethod"> <Details> <![CDATA[ <p>Looks for methods that are declared as abstract that override concrete methods in a superclass. Doing this casts away the implementation of the superclass, and breaks the contract as set forth by the parent class.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CustomBuiltXML"> <Details> <![CDATA[ <p>Looks for methods that build XML based strings by concatenating 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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.BloatedSynchronizedBlock"> <Details> <![CDATA[ <p>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.</p> <p>It is a slow detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ConstantListIndex"> <Details> <![CDATA[ <p>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, or even a map with informative key names would be better.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SloppyClassReflection"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ArrayWrappedCallByReference"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SluggishGui"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NeedlessInstanceRetrieval"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.DateComparison"> <Details> <![CDATA[ <p>Looks for inefficient comparison of Date objects using two comparisons when one would do.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousWaitOnConcurrentObject"> <Details> <![CDATA[ <p>Looks for calls to the wait method on mutexes defined in the java.util.concurrent package where it is likely that await was intended.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.JDBCVendorReliance"> <Details> <![CDATA[ <p>Looks for uses of JDBC vendor specific classes and methods making the database access code non-portable.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PossibleMemoryBloat"> <Details> <![CDATA[ <p>Looks for classes that have usage patterns that may cause memory bloat to occur. This can occur with classes 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. Other cases are use of JAXBContexts stored recreated over and over again, instead of using a cached instance. Such class fields are likely causes of memory bloat.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.LocalSynchronizedCollection"> <Details> <![CDATA[ <p>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.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.FieldCouldBeLocal"> <Details> <![CDATA[ <p>Looks for classes that define fields that are used in a local-only fashion, specifically private fields that are accessed first in each method with a store vs. a load.</p> <p>It is a slow detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NonOwnedSynchronization"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NonRecycleableTaglibs"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.Section508Compliance"> <Details> <![CDATA[ <p>Looks for violation of Section 508, Accessibility for People with Disabilities Act.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UseEnumCollections"> <Details> <![CDATA[ <p>Looks for use of sets and maps using enums. It is more efficient to use EnumSet or EnumMap.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SQLInLoop"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NeedlessMemberCollectionSynchronization"> <Details> <![CDATA[ <p>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.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.InheritanceTypeChecking"> <Details> <![CDATA[ <p>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.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.StaticArrayCreatedInMethod"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PossiblyRedundantMethodCalls"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UseToArray"> <Details> <![CDATA[ <p>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()]).</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.LostExceptionStackTrace"> <Details> <![CDATA[ <p>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.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UseCharacterParameterizedMethod"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.TailRecursion"> <Details> <![CDATA[ <p>Looks for methods that make recursive calls to themselves 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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnrelatedReturnValues"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PossibleIncompleteSerialization"> <Details> <![CDATA[ <p>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 class.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousComparatorReturnValues"> <Details> <![CDATA[ <p>Looks for classes that implement Comparator or Comparable, and whose compare or compareTo methods return constant values only, but that don't represent the three possible choices (a negative number, 0, and a positive number).</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SillynessPotPourri"> <Details> <![CDATA[ <p>Looks for a potpourri of small problems that do not fit into a common pattern.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.BloatedAssignmentScope"> <Details> <![CDATA[ <p><em>THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD</em></p> <p>Looks for assignments to variables in a scope larger than their 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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SpoiledChildInterfaceImplementor"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.DeletingWhileIterating"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UseSplit"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousJDKVersionUse"> <Details> <![CDATA[ <p>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 <code>-source</code> and <code>-target</code> options of the javac compiler, and specify a target that is less than the JDK version of the javac compiler.</p> <p>It relies on the system property <code>-Dfb-contrib.sjvu.jdkhome=/path/to/older/jdk/to/check"</code> to specify what JDK to compare against. On linux, you may need to give file permissions to findbugs to read these directories. If this property is not set, this detector does nothing.</p> <p>It is a slow detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UseAddAll"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.MethodReturnsConstant"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NeedlessCustomSerialization"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.MisleadingOverloadModel"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ExceptionSoftening"> <Details> <![CDATA[ <p>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 superclass contracts not to throw checked exceptions but appear owned by the same author. Next are methods constrained by interface or superclass contracts and throw other types of checked exceptions. Most egregious are methods not constrained by any interface or superclass contract.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ConfusingFunctionSemantics"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnitTestAssertionOddities"> <Details> <![CDATA[ <p>Looks for JUnit or TestNG test case methods that use assertions with odd parameters. Included in this is: <ul> <li>Passing a constant as the second (actual) parameter in a JUnit test</li> <li>Not using the three parameter version of asserts for doubles</li> <li>Passing true or false as the first parameter instead of using assertTrue, or assertFalse</li> <li>Using the assert keyword</li> </ul> </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousCloneAlgorithm"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.WeakExceptionMessaging"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousClusteredSessionSupport"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.LoggerOddities"> <Details> <![CDATA[ <p>Looks for odd patterns of use of Logger classes from either Log4j, Log4j2, SLF4J or Commons Logging.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.IncorrectInternalClassUse"> <Details> <![CDATA[ <p>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.</p> Packages that shouldn't be used are: <ul> <li>sun.xxx</li> <li>org.apache.xerces.xxx</li> <li>org.apache.xalan.xxx</li> </ul> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.DubiousSetOfCollections"> <Details> <![CDATA[ <p>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.</p> <p>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.</p> <p>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.</p> <p>If you wish to keep a collection of collections, the outer collection should probably be a list to avoid these problems.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.BogusExceptionDeclaration"> <Details> <![CDATA[ <p>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.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnnecessaryNewNullCheck"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.DeprecatedTypesafeEnumPattern"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.TristateBooleanPattern"> <Details> <![CDATA[ <p>Looks for methods that are declared to return a Boolean, but return a null value. As this now allows the method to return three values, the use of Boolean is dubious. It would be better to just define a new enumeration with three values, and return that.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousUninitializedArray"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.InappropriateToStringUse"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.InconsistentKeyNameCasing"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.OverzealousCasting"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PoorlyDefinedParameter"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NonSymmetricEquals"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ContraVariantArrayAssignment"> <Details> <![CDATA[ <p>Finds contravariant array assignments. Since arrays are mutable data structures, their use must be restricted to covariant or invariant usage.</p> <pre><code> class A {} class B extends A {} B[] b = new B[2]; A[] a = b; a[0] = new A(); // results in ArrayStoreException (Runtime) </code></pre> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NonFunctionalField"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousNullGuard"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.MoreDumbMethods"> <Details> <![CDATA[ <p>This detector looks for calls to more pointless or deprecated methods.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ReflectionOnObjectMethods"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ImproperPropertiesUse"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PossibleConstantAllocationInLoop"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.WriteOnlyCollection"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UseVarArgs"> <Details> <![CDATA[ <p>This detector looks for problems and possibilities to use var args better. Specially looks for <ul> <li>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</li> <li>classes that have samed named vararg and non vararg methods not clearly differentiated.</li> <li>Explicitly passing null to a var arg parameter</li></ul>.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PossibleUnsuspectedSerialization"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SideEffectConstructor"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousGetterSetterUse"> <Details> <![CDATA[ <p>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 corollary getter, like this:</p> <pre><code> person.setAge(person.getAge()); </code></pre> <p>Typically this is a copy paste typo.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.LingeringGraphicsObjects"> <Details> <![CDATA[ <p>This detector looks for creation of java.awt.Graphics objects that do not have the <code>.dispose()</code> 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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.StackedTryBlocks"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CommonsEqualsBuilderToEquals"> <Details> <![CDATA[ <p>This detector looks for uses for commons-lang EqualsBuilder where the result of equals() is returned instead of calling the method isEquals().</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CommonsHashcodeBuilderToHashcode"> <Details> <![CDATA[ <p>This detector looks for uses for commons-lang <code>HashCodeBuilder</code> where the result of <code>hashCode()</code> is returned instead of calling the method <code>toHashCode()</code>.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CommonsStringBuilderToString"> <Details> <![CDATA[ <p>This detector looks for uses for commons-lang <code>ToStringBuilder</code> where the result of <code>toString()</code> is returned without an intermediate invocation of append().</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CompareClassNameEquals"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.BackportReusePublicIdentifiers"> <Details> <![CDATA[ <p>Detects use of Backport Utils concurrent classes from Emory, or Time classes from ThreeTen. Updated/efficient versions of classes from emory are available in versions of the JDK 5.0 and higher, and in JDK 8.0 and higher for ThreeTen, and these classes should only be used if you are targeting a JDK lower than this.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CloneUsability"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ConfusingArrayAsList"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PresizeCollections"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnboundMethodTemplateParameter"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.NonProductiveMethodCall"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ArrayIndexOutOfBounds"> <Details> <![CDATA[ <p>Looks for questionable load/stores to array elements. <ul> <li> 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.</li> <li> Looks for stores to array elements where the array itself appears to have not been allocated. </li> </ul> </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.InvalidConstantArgument"> <Details> <![CDATA[ <p>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. </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CollectionNamingConfusion"> <Details> <![CDATA[ <p>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 </p> <p>List<String> mySet;</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.PoorMansEnum"> <Details> <![CDATA[ <p>Looks for fields defined with simple types, (int, String, etc) that are used like enums. Specifically fields that are only assigned a set of constant values. This variable probably should be redefined as an enum. </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnusedParameter"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.FindClassCircularDependencies"> <Details> <![CDATA[ <p>This detector looks for circular dependencies among classes. </p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ModifyingUnmodifiableCollection"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.HangingExecutors"> <Details> <![CDATA[ <p>Three detectors for hanging ExecutorServices, that is, ExecutorServices that never get a call to shutdown, which can potentially cause the JVM to not exit.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.HttpClientProblems"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.Unjitable"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ConflictingTimeUnits"> <Details> <![CDATA[ <p>Looks for methods that perform arithmetic operations on values representing time where the time unit is incompatible, e.g. adding a millisecond value to a nanosecond value. </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.CharsetIssues"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ContainsBasedConditional"> <Details> <![CDATA[ <p>Looks for complex <code>if</code> 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 grows it is much cleaner to build a static set of the possible values, and use the <code>contains</code> method on that set. This will shorten the code, and make it more self documenting.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.OverlyPermissiveMethod"> <Details> <![CDATA[ <p>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. Giving methods 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 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 erroneously report it.</p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.StringifiedTypes"> <Details> <![CDATA[ <p>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 impersonation are storing: <ul> <li>The result of a toString call</li> <li>Strings built from parsing or building strings from other objects, such as "1,2,3,4" or "Project:3"</li> </ul> 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. </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousLoopSearch"> <Details> <![CDATA[ <p>Looks for methods that assign a value to a variable in an "if equals" conditional in a loop, but do 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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ConflatingResourcesAndFiles"> <Details> <![CDATA[ <p>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.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ImmatureClass"> <Details> <![CDATA[ <p>Looks for classes that are not fully complete from a usability point of view, making them more difficult to use than they should be. Things such as <ul> <li>Using the default package</li> <li>Missing hashCode/equals</li> <li>Missing toString() method</li> <li>Using autogenerated parameter names</li> </ul> </p> <p>It is a moderately fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.JAXRSIssues"> <Details> <![CDATA[ <p>Looks for problems with the use of the JAX-RS specification.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.JPAIssues"> <Details> <![CDATA[ <p>Looks for problems with the use of the JPA specification, including Spring's support of JPA</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuboptimalExpressionOrder"> <Details> <![CDATA[ <p>Looks for conditional expressions that are a combination of simple local variable (in)equalities and tests on the results of method calls, where the method calls are done first. By placing the simple conditions first you may eliminate costly calls in certain cases. This assumes that the method calls do not have side effects that should happen always.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.IOIssues"> <Details> <![CDATA[ <p>Looks for various issues around doing I/O with streams and reader/writers, and compression of byte buffers.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.DubiousMapCollection"> <Details> <![CDATA[ <p>Looks for use of maps that are private fields in a List-only way, that is, maps that are created in constructors or static initializers, and are only iterated over. Often this is done because the Map allows for two values, as opposed to a List. The fix is to just create a List of some object that holds all the values.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.BuryingLogic"> <Details> <![CDATA[ <p>Looks for methods that needlessly push a large chunk of code to the right through indenting with braces. The code is basically an if/else-then-return structure. The "if true" test does the bulk of the logic, and the else just returns. It is more readable if the bulk of the logic is moved as far to the left in the method as is possible. </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.WiringIssues"> <Details> <![CDATA[ <p>Looks for various issues around @Autowired/@Inject fields in DI classes</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ConcurrentCollectionIssues"> <Details> <![CDATA[ <p>Looks for problems with using concurrent collections. <ul> <li>Adding a collection as a value of a Concurrent map, without the use of putIfAbsent</li> </ul> </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UseTryWithResources"> <Details> <![CDATA[ <p>Looks for use of auto-closeable resources in JDK 7 or later that are not using the try-with-resources paradigm. To avoid problems, and ease the reader, use of try-with-resources is recommended</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousShadedClassUse"> <Details> <![CDATA[ <p>Looks for use of shaded methods from 3rd-party jars, created by tools such as the Maven shade plugin. These methods are from classes that have been included in a jar, for internal use, and are copies of real 3rd-party jars. It is likely you meant to use the real class from the real jar, but your IDE picked the wrong import to use. </p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnsynchronizedSingletonFieldWrites"> <Details> <![CDATA[ <p>Looks for writes to fields of classes that are believed to be classes used only as Singletons. These classes include Enums, as well as spring beans that are Singleton scoped.</p> <p>It is a fast detector.</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.OptionalIssues"> <Details> <![CDATA[ <p>Looks for various issues with the use of the java.util.Optional class.</p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.UnnecessaryApiConversion"> <Details> <![CDATA[ <p>Looks for code that appears to be using two forms of similar apis: an older one, and a new one. It finds code that creates newer api objects by first instantiating older api objects, and converting them into the new form. It is simpler just to create the new object directly.</p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ReflectionIssues"> <Details> <![CDATA[ <p>Looks for issues around the use of java reflection.</p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.AnnotationIssues"> <Details> <![CDATA[ <p>Looks for issues around use of standard annotations</p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.MapUsageIssues"> <Details> <![CDATA[ <p>Looks for dubious usage patterns around the Map interface</p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.ListUsageIssues"> <Details> <![CDATA[ <p>Looks for dubious usage patterns around the List interface</p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.FunctionalInterfaceIssues"> <Details> <![CDATA[ <p>Looks for various issues around the use of @FunctionalInterfaces.</p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SetUsageIssues"> <Details> <![CDATA[ <p>Looks for various issues around the use of the Set interface</p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.SuspiciousArgumentTypes"> <Details> <![CDATA[ <p>Looks for method calls where the arguments passed seem oddly typed for the use they are intended for. </p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.EnumIssues"> <Details> <![CDATA[ <p>Looks for various issues with uses of enum objects. </p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.detect.AkkaIssues"> <Details> <![CDATA[ <p>Looks for various issues with uses of Akka. </p> <p>It is a fast detector</p> ]]> </Details> </Detector> <Detector class="com.mebigfatguy.fbcontrib.debug.OCSDebugger"> <Details></Details> </Detector> <!-- BugPattern --> <BugPattern type="ISB_INEFFICIENT_STRING_BUFFERING"> <ShortDescription>Method passes simple concatenating string in StringBuffer or StringBuilder append</ShortDescription> <LongDescription>Method {1} passes simple concatenating string in StringBuffer or StringBuilder append</LongDescription> <Details> <![CDATA[ <p>This method uses <code>StringBuffer</code> or <code>StringBuilder</code>'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 <code>StringBuffer</code> or <code>StringBuilder</code> class.</p> <p> Java will implicitly use StringBuilders, which can make this hard to detect or fix. For example, <br/> <pre><code> StringBuilder sb = new StringBuilder(); for (Map.Entry<Integer, String> e : map.entrySet()) { sb.append(e.getKey() + e.getValue()); //bug detected here } </code></pre><br/> gets automatically turned into something like: <br/> <pre><code> StringBuilder sb = new StringBuilder(); for (Map.Entry<Integer, String> e : map.entrySet()) { StringBuilder tempBuilder = new StringBuilder(); tempBuilder.append(e.getKey()); tempBuilder.append(e.getValue()); <b>sb.append(tempBuilder.toString());</b> //this isn't too efficient } </code></pre><br/> which involves a temporary <code>StringBuilder</code>, which is completely unnecessary. To prevent this from happening, simply do:<br/> <pre><code> StringBuilder sb = new StringBuilder(); for (Map.Entry<Integer, String> e : map.entrySet()) { sb.append(e.getKey()); sb.append(e.getValue()); } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="ISB_EMPTY_STRING_APPENDING"> <ShortDescription>Method concatenates an empty string to effect type conversion</ShortDescription> <LongDescription>Method {1} concatenates an empty string to effect type conversion</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="ISB_TOSTRING_APPENDING"> <ShortDescription>Method concatenates the result of a toString() call</ShortDescription> <LongDescription>Method {1} concatenates the result of a toString() call</LongDescription> <Details> <![CDATA[ <p>This method concatenates the output of a <code>toString()</code> call into a <code>StringBuffer</code> or <code>StringBuilder</code>. 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 <code>NullPointerException</code>s, and is easier to read.</p> <p> Keep in mind that Java compiles simple <code>String</code> concatenation to use <code>StringBuilder</code>s, so you may see this bug even when you don't use <code>StringBuilder</code>s explicitly. </p> <p> Instead of: <br/> <pre><code> StringBuilder builder = ...; builder.append(someObj.toString()); ... System.out.println("Problem with the object :" + someObj.toString()); </code></pre> just do: <br/> <pre><code> StringBuilder builder = ... builder.append(someObj); ... System.out.println("Problem with the object :" + someObj); </code></pre> to avoid the possibility of <code>NullPointerException</code>s when someObj is <code>null</code>. </p> ]]> </Details> </BugPattern> <BugPattern type="SCI_SYNCHRONIZED_COLLECTION_ITERATORS"> <ShortDescription>Method creates iterators on synchronized collections</ShortDescription> <LongDescription>Method {1} creates iterators on synchronized collections</LongDescription> <Details> <![CDATA[ <p>This method uses a synchronized collection, built from Collections.synchronizedXXXX, but accesses it through an iterator. Since an iterator is, by definition, multithreading-unsafe, this is a conflict in concept. When using iterators, you should do the synchronization manually.</p> ]]> </Details> </BugPattern> <BugPattern type="CC_CYCLOMATIC_COMPLEXITY"> <ShortDescription>Method is excessively complex</ShortDescription> <LongDescription>Method {1} is excessively complex, with a cyclomatic complexity of {3}</LongDescription> <Details> <![CDATA[ <p>This method has a high cyclomatic complexity figure, which represents 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.</p> ]]> </Details> </BugPattern> <BugPattern type="OCP_OVERLY_CONCRETE_PARAMETER"> <ShortDescription>Method needlessly defines parameter with concrete classes</ShortDescription> <LongDescription>{1}: {3}</LongDescription> <Details> <![CDATA[ <p>This method uses concrete classes for parameters when only methods defined in an implemented interface or superclass are used. Consider increasing the abstraction of the interface to make low impact changes easier to accomplish in the future.</p> <p>Take the following example:<br/> <pre><code> private void appendToList(ArrayList<String> list) { if (list.size() < 100) { list.add("Foo"); } } </code></pre> The parameter list is currently defined as an <code>ArrayList</code>, which is a concrete implementation of the <code>List</code> interface. Specifying <code>ArrayList</code> is unnecessary here, because we aren't using any <code>ArrayList</code>-specific methods (like <code>ensureCapacity()</code> or <code>trimToSize()</code>). Instead of using the concrete definition, it is better to do something like:<br/> <pre><code> private void appendToList(List<String> list) { ... </code></pre> If the design ever changes, e.g. a <code>LinkedList</code> is used instead, this code won't have to change. </p> <p>IDEs tend to have tools to help generalize parameters. For example, in Eclipse, the refactoring tool <a href="http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fref-menu-refactor.htm">Generalize Declared Type</a> helps find an appropriate level of concreteness.</p> ]]> </Details> </BugPattern> <BugPattern type="LII_LIST_INDEXED_ITERATING"> <ShortDescription>Method uses integer based for loops to iterate over a List</ShortDescription> <LongDescription>Method {1} uses integer based for loops to iterate over a List</LongDescription> <Details> <![CDATA[ <p>This method uses an integer-based <code>for</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="UCC_UNRELATED_COLLECTION_CONTENTS"> <ShortDescription>Method adds unrelated types to collection or array</ShortDescription> <LongDescription>Method {1} adds unrelated types to collection or array</LongDescription> <Details> <![CDATA[ <p>This method adds unrelated objects to a collection or array, requiring careful and brittle data access to that collection. Create a separate class with the properties needed, and add an instance of this class to the collection or array, if possible.</p> ]]> </Details> </BugPattern> <BugPattern type="DRE_DECLARED_RUNTIME_EXCEPTION"> <ShortDescription>Method declares RuntimeException in throws clause</ShortDescription> <LongDescription>Method {1} declares RuntimeException in throws clause</LongDescription> <Details> <![CDATA[ <p>This method declares a RuntimeException derived class in its throws clause. This may indicate a misunderstanding as to how unchecked exceptions are handled. If it is felt that a RuntimeException is so prevalent that it should be declared for documentation purposes, using javadoc's @throws clause is a better idea, as it doesn't needless pollute the method signature,</p> ]]> </Details> </BugPattern> <BugPattern type="CE_CLASS_ENVY"> <ShortDescription>Method excessively uses methods of another class</ShortDescription> <LongDescription>Method {1} excessively uses methods of another class</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="LSC_LITERAL_STRING_COMPARISON"> <ShortDescription>Method makes literal string comparisons passing the literal as an argument</ShortDescription> <LongDescription>Method {1} makes literal string comparisons passing the literal as an argument</LongDescription> <Details> <![CDATA[ <p>This line is in the form of <br/> <pre><code>String str = ... str.equals("someOtherString"); //or str.compareTo("someOtherString");</code></pre> </p> <p>A <code>NullPointerException</code> may occur if the String variable <code>str</code> is <code>null</code>. If instead the code was restructured to<br/> <pre><code>String str = ... "someOtherString".equals(str); //or "someOtherString".compareTo(str);</code></pre><br/> that is, call <code>equals()</code> or <code>compareTo()</code> on the string literal, passing the variable as an argument, then this exception could never happen as both <code>equals()</code> and <code>compareTo()</code> check for <code>null</code>.</p> ]]> </Details> </BugPattern> <BugPattern type="PCOA_PARTIALLY_CONSTRUCTED_OBJECT_ACCESS"> <ShortDescription>Constructor makes call to non-final method</ShortDescription> <LongDescription>Constructor {1} makes call to non-final method</LongDescription> <Details> <![CDATA[ <p>This constructor makes a call to a non-final method. Since this method can be overridden, a subclass' 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.</p> ]]> </Details> </BugPattern> <BugPattern type="DLC_DUBIOUS_LIST_COLLECTION"> <ShortDescription>Class defines List based fields but uses them like Sets</ShortDescription> <LongDescription>Class {0} defines List based fields but uses them like Sets</LongDescription> <Details> <![CDATA[ <p>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. If the list is known to only contain a small number of items (3, 4, etc), then it doesn't matter. Otherwise, consider changing this field's implementation to a set-based one. If order of iteration is important to maintain insert order, perhaps consider a LinkedHashSet.</p> ]]> </Details> </BugPattern> <BugPattern type="PL_PARALLEL_LISTS"> <ShortDescription>Class defines two or more one for one associated lists or arrays</ShortDescription> <LongDescription>Class {0} defines two or more one for one associated lists or arrays</LongDescription> <Details> <![CDATA[ <p>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:<br/> <pre><code> List<String> words = new ArrayList<String>(); List<Integer> wordCounts = new ArrayList<String>(); </code></pre> where the elements of the list at index 0 are related, the elements at index 1 are related and so on. </p> <p> 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:<br/> <pre><code> private class WordAndCount{public String word; public int count} List<WordAndCount> wordsAndCounts = new ArrayList<WordAndCount>(); //or, for just two elements Map<String,Integer> wordCounts = new HashMap<String,Integer>(); </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="FP_FINAL_PARAMETERS"> <ShortDescription>Method does not define a parameter as final, but could</ShortDescription> <LongDescription>Method {1} does not define one or more parameters as final, but could</LongDescription> <Details> <![CDATA[ <p>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.</p> <p>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. Its only use is to clarify the coder's 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 </p> ]]> </Details> </BugPattern> <BugPattern type="ACEM_ABSTRACT_CLASS_EMPTY_METHODS"> <ShortDescription>Empty method could be declared abstract</ShortDescription> <LongDescription>Empty method {1} could be declared abstract</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="MAC_MANUAL_ARRAY_COPY"> <ShortDescription>Method copies arrays manually</ShortDescription> <LongDescription>Method {1} copies arrays manually</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="FPL_FLOATING_POINT_LOOPS"> <ShortDescription>Method uses floating point indexed loops</ShortDescription> <LongDescription>Method {1} uses floating point indexed loops</LongDescription> <Details> <![CDATA[ <p>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.</p> <p>Example: <pre><code> for (float f = 1.0f; f <= 10.0f; f += 0.1f) { System.out.println(f); } </code></pre> The last value printed may not be 10.0, but instead might be 9.900001 or such. </p> ]]> </Details> </BugPattern> <BugPattern type="NCMU_NON_COLLECTION_METHOD_USE"> <ShortDescription>Method uses old non collections interface methods</ShortDescription> <LongDescription>Method {1} uses old non collections interface methods</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="CAO_CONFUSING_AUTOBOXED_OVERLOADING"> <ShortDescription>Class defines methods which confuse Character with int parameters</ShortDescription> <LongDescription>Class {0} defines methods which confuse Character with int parameters</LongDescription> <Details> <![CDATA[ <p>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 it does not.</p> ]]> </Details> </BugPattern> <BugPattern type="AFBR_ABNORMAL_FINALLY_BLOCK_RETURN"> <ShortDescription>Method has abnormal exit from finally block</ShortDescription> <LongDescription>Method {1} has abnormal exit from finally block</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SMII_STATIC_METHOD_INSTANCE_INVOCATION"> <ShortDescription>Method calls static method on instance reference</ShortDescription> <LongDescription>Method {1} calls static method on instance reference</LongDescription> <Details> <![CDATA[ <p>This method makes a static method call on an instance reference. For reading comprehension of the code it 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.</p> ]]> </Details> </BugPattern> <BugPattern type="STS_SPURIOUS_THREAD_STATES"> <ShortDescription>Method calls wait, notify or notifyAll on a Thread instance</ShortDescription> <LongDescription>Method {1} calls wait, notify or notifyAll on a Thread instance</LongDescription> <Details> <![CDATA[ <p>This method invokes the methods <code>wait</code>, <code>notify</code> or <code>notifyAll</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="NAB_NEEDLESS_AUTOBOXING_CTOR"> <ShortDescription>Method passes primitive wrapper to same primitive wrapper constructor</ShortDescription> <LongDescription>Method {1} passes primitive wrapper to same primitive wrapper constructor</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="NAB_NEEDLESS_BOXING_STRING_CTOR"> <ShortDescription>Method passes parsed string to primitive wrapper constructor</ShortDescription> <LongDescription>Method {1} passes parsed string to primitive wrapper constructor</LongDescription> <Details> <![CDATA[ <p>This method passes a primitive value retrieved from a <code>BoxedPrimitive.parseBoxedPrimitive("1")</code> call to the same class's constructor. It is simpler to just pass the string to the BoxedPrimitive constructor or, better yet, use the static valueOf.</p> <p>Instead of something like:<br/> <pre><code> Boolean bo = new Boolean(Boolean.parseBoolean("true")); Float f = new Float(Float.parseFloat("1.234")); </code></pre> Simply do: <br/> <pre><code> Boolean bo = new Boolean("true"); Float f = new Float("1.234"); </code></pre> or, to be more memory efficient: <br/> <pre><code> Boolean bo = Boolean.valueOf("true"); Float f = Float.valueOf("1.234"); </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="NAB_NEEDLESS_AUTOBOXING_VALUEOF"> <ShortDescription>Method passes primitive wrapper to Wrapper class valueOf method</ShortDescription> <LongDescription>Method {1} passes primitive wrapper to Wrapper class valueOf method</LongDescription> <Details> <![CDATA[ <p>This method passes a wrapped primitive object to the same class' <code>valueOf</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="NAB_NEEDLESS_BOXING_PARSE"> <ShortDescription>Method converts String to primitive using excessive boxing</ShortDescription> <LongDescription>Method {1} converts String to primitive using excessive boxing</LongDescription> <Details> <![CDATA[ <p>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. </p> <p>Instead of something like:<br/> <pre><code> 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 } </code></pre> Simply do: <br/> <pre><code> public int someMethod(String data) { long l = Long.parseLong(data); float f = Float.parseFloat(data); return Integer.parseInt(data); } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="NAB_NEEDLESS_BOXING_VALUEOF"> <ShortDescription>Method converts String to boxed primitive using excessive boxing</ShortDescription> <LongDescription>Method {1} converts String to boxed primitive using excessive boxing</LongDescription> <Details> <![CDATA[ <p>This method passes a String to a wrapped primitive object's parse method, which in turn calls the <code>valueOf</code> 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.</p> <p>Instead of something like:<br/> <pre><code> Boolean bo = Boolean.valueOf(Boolean.parseBoolean("true")); Float f = Float.valueOf(Float.parseFloat("1.234")); </code></pre> Simply do: <br/> <pre><code> Boolean bo = Boolean.valueOf("true"); Float f = Float.valueOf("1.234"); </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="NAB_NEEDLESS_BOX_TO_UNBOX"> <ShortDescription>Method creates Boxed primitive from primitive only to get primitive value</ShortDescription> <LongDescription>Method {1} creates Boxed primitive from primitive only to get primitive value</LongDescription> <Details> <![CDATA[ <p>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.</p> <p>Instead of something like:<br/> <pre><code> boolean bo = new Boolean(true).booleanValue(); float f = new Float(1.234f).floatValue(); </code></pre> Simply do: <br/> <pre><code> boolean bo = true; float f = 1.234f; </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="NAB_NEEDLESS_BOX_TO_CAST"> <ShortDescription>Method creates Boxed primitive from primitive only to cast to another primitive type</ShortDescription> <LongDescription>Method {1} creates Boxed primitive from primitive only to cast to another primitive type</LongDescription> <Details> <![CDATA[ <p>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.</p> <p>Instead of something like:<br/> <pre><code> double someDouble = ... float f = new Double(someDouble).floatValue(); int someInt = ... byte b = new Integer(someInt).byteValue(); </code></pre> Simply do: <br/> <pre><code> double someDouble = ... float f = (float) someDouble; int someInt = ... byte b = (byte)someInt; </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="NAB_NEEDLESS_BOOLEAN_CONSTANT_CONVERSION"> <ShortDescription>Method needlessly boxes a boolean constant</ShortDescription> <LongDescription>Method {1} needlessly boxes a boolean constant</LongDescription> <Details> <![CDATA[ <p>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 <br/> <pre><code> boolean b = true; boolean b = false; </code></pre> or <br/> <pre><code> Boolean b = Boolean.TRUE; Boolean b = Boolean.FALSE; </code></pre> </p> <p>Be aware that this boxing happens automatically when you might not expect it. For example, <br/> <pre><code> Map<String, Boolean> statusMap = ... public Boolean someMethod() { statusMap.put("foo", true); //the "true" here is boxed return false; //the "false" here is boxed } </code></pre> has two cases of this needless autoboxing. This can be made more efficient by simply substituting in the constant values: <br/> <pre><code> Map<String, Boolean> statusMap = ... public Boolean someMethod() { statusMap.put("foo", Boolean.TRUE); return Boolean.FALSE; } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="USBR_UNNECESSARY_STORE_BEFORE_RETURN"> <ShortDescription>Method stores return result in local before immediately returning it</ShortDescription> <LongDescription>Method {1} stores return result in local before immediately returning it</LongDescription> <Details> <![CDATA[ <p>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.</p> <p> Instead of the following: <br/> <pre><code> 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; } </code></pre> Simply change the method to return the result of the division: <br/> <pre><code> public float average(int[] arr) { float sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } <b>return sum / arr.length;</b> //Change } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="COM_COPIED_OVERRIDDEN_METHOD"> <ShortDescription>Method is implemented with an exact copy of its superclass' method</ShortDescription> <LongDescription>Method {1} is implemented with an exact copy of its superclass' method</LongDescription> <Details> <![CDATA[ <p>This method is implemented using an exact copy of its superclass method's implementation, which usually means that this method can just be removed.</p> ]]> </Details> </BugPattern> <BugPattern type="COM_PARENT_DELEGATED_CALL"> <ShortDescription>Method merely delegates to its superclass's version</ShortDescription> <LongDescription>Method {1} merely delegates to its superclass's version</LongDescription> <Details> <![CDATA[ <p>This method is implemented to just delegate its implementation by calling the superclass method with the same signature. This method can just be removed.</p> ]]> </Details> </BugPattern> <BugPattern type="ABC_ARRAY_BASED_COLLECTIONS"> <ShortDescription>Method uses array as basis of collection</ShortDescription> <LongDescription>Method {1} uses array as basis of collection</LongDescription> <Details> <![CDATA[ <p>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 <code>equals</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="ODN_ORPHANED_DOM_NODE"> <ShortDescription>Method creates DOM node but doesn't attach it to a document</ShortDescription> <LongDescription>Method {1} creates DOM node but doesn't attach it to a document</LongDescription> <Details> <![CDATA[ <p>This method creates a DOM node but does not attach it to a DOM document.</p> ]]> </Details> </BugPattern> <BugPattern type="AOM_ABSTRACT_OVERRIDDEN_METHOD"> <ShortDescription>Abstract method overrides a concrete implementation</ShortDescription> <LongDescription>Abstract method {1} overrides a concrete implementation</LongDescription> <Details> <![CDATA[ <p>This abstract method is derived from a concrete method implementation. It is highly suspect that the superclass method's implementation would be cast away.</p> ]]> </Details> </BugPattern> <BugPattern type="CBX_CUSTOM_BUILT_XML"> <ShortDescription>Method builds XML strings through ad hoc concatenation</ShortDescription> <LongDescription>Method {1} builds XML strings through ad hoc concatenation</LongDescription> <Details> <![CDATA[ <p>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 cleaner to build XML structures in external files that are read in and transformed into the final product, through modification by Transformer.setParameter.</p> ]]> </Details> </BugPattern> <BugPattern type="BSB_BLOATED_SYNCHRONIZED_BLOCK"> <ShortDescription>Method overly synchronizes a block of code</ShortDescription> <LongDescription>Method {1} overly synchronizes a block of code</LongDescription> <Details> <![CDATA[ <p>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 <code>this</code>. For better performance, move the code that accesses local variables only above the synchronized block, and leave the synchronized block only for field accesses, or access to <code>this</code>.</p> ]]> </Details> </BugPattern> <BugPattern type="CLI_CONSTANT_LIST_INDEX"> <ShortDescription>Method accesses list or array with constant index</ShortDescription> <LongDescription>Method {1} accesses list or array with constant index</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SCR_SLOPPY_CLASS_REFLECTION"> <ShortDescription>Method accesses statically bound class with Class.forName</ShortDescription> <LongDescription>Method {1} accesses statically bound class with Class.forName</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="AWCBR_ARRAY_WRAPPED_CALL_BY_REFERENCE"> <ShortDescription>Method uses 1 element array to simulate call by reference</ShortDescription> <LongDescription>Method {1} uses 1 element array to simulate call by reference</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SG_SLUGGISH_GUI"> <ShortDescription>Method performs time consuming operation in GUI thread</ShortDescription> <LongDescription>Method {1} performs time consuming operation in GUI thread</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="NIR_NEEDLESS_INSTANCE_RETRIEVAL"> <ShortDescription>Method retrieves instance to load static member</ShortDescription> <LongDescription>Method {1} retrieves instance to load static member</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="DDC_DOUBLE_DATE_COMPARISON"> <ShortDescription>Method uses two date comparisons when one would do</ShortDescription> <LongDescription>Method {1} uses two date comparisons when one would do</LongDescription> <Details> <![CDATA[ <p>This method compares dates with two comparisons, rather than using the reverse comparison. So this pattern</p> <pre><code> if ((date1.equals( date2 )) || (date1.after( date2 ))) </code></pre> could become:<br/> <pre><code> if (date1.compareTo( date2 ) >= 0) </code></pre><br/> and<br/> <pre><code> if ((date1.equals( date2 )) || (date1.before( date2 ))) </code></pre> could become <br/> <pre><code> if (date1.compareTo( date2 ) <= 0) </code></pre><br/> and<br/> <pre><code> if ((date1.before( date2 )) || (date1.after( date2 ))) </code></pre> could become<br/> <pre><code> if (!date1.equals( date2 )) </code></pre> ]]> </Details> </BugPattern> <BugPattern type="SWCO_SUSPICIOUS_WAIT_ON_CONCURRENT_OBJECT"> <ShortDescription>Method calls wait when await was probably intended</ShortDescription> <LongDescription>Method {1} calls wait when await was probably intended</LongDescription> <Details> <![CDATA[ <p>This method calls wait() on a mutex defined in the java.util.concurrent package. These classes define <code>await</code>, instead of <code>wait</code>, and it is most likely that <code>await</code> was intended.</p> ]]> </Details> </BugPattern> <BugPattern type="JVR_JDBC_VENDOR_RELIANCE"> <ShortDescription>Method uses JDBC vendor specific classes and methods</ShortDescription> <LongDescription>Method {1} uses JDBC vendor specific classes and methods</LongDescription> <Details> <![CDATA[ <p>This method uses JDBC vendor-specific classes and methods to perform database work. This makes the code specific to this vendor, and unable to run on other databases.</p> ]]> </Details> </BugPattern> <BugPattern type="PMB_POSSIBLE_MEMORY_BLOAT"> <ShortDescription>Potential memory bloat in static field</ShortDescription> <LongDescription>Class {0} defines static field "{1}" which appears to allow memory bloat</LongDescription> <Details> <![CDATA[ <p>This class defines static fields that are <code>Collection</code>s, <code>StringBuffer</code>s, or <code>StringBuilder</code>s 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 <br/> {<code>add()</code>, <code>append()</code>, <code>offer()</code>, <code>put()</code>, ...} <br/> with no method calls to removal methods like<br/> {<code>clear()</code>, <code>delete()</code>, <code>pop()</code>, <code>remove()</code>, ...}<br/> This means that the collection in question can only ever increase in size, which is a potential cause of memory bloat.</p> <p> If this collection is a list, set or otherwise of static things (e.g. a List<String> for month names), consider adding all of the elements in a static initializer, which can only be called once:<br/> <pre><code> private static List<String> monthNames = new ArrayList<String>(); static { monthNames.add("January"); monthNames.add("February"); monthNames.add("March"); ... } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="PMB_INSTANCE_BASED_THREAD_LOCAL"> <ShortDescription>Field is an instance based ThreadLocal variable</ShortDescription> <LongDescription>Field {1} is an instance based ThreadLocal variable</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="PMB_LOCAL_BASED_JAXB_CONTEXT"> <ShortDescription>Local JAXBContext created on demand</ShortDescription> <LongDescription>Method {1} createa a local JAXBContext on demand</LongDescription> <Details> <![CDATA[ <p>This method creates a JAXBContext and stores it in a local variable. This implies that this JAXBContext is created each time on demand, which will cause memory bloat issues. It is better to either create this instance as a static field, or hold onto it with a ConcurrentHashMap, or such. See https://javaee.github.io/jaxb-v2/doc/user-guide/ch03.html#other-miscellaneous-topics-performance-and-thread-safety </p> ]]> </Details> </BugPattern> <BugPattern type="LSYC_LOCAL_SYNCHRONIZED_COLLECTION"> <ShortDescription>Method creates local variable-based synchronized collection</ShortDescription> <LongDescription>Method {1} creates local variable-based synchronized collection</LongDescription> <Details> <![CDATA[ <p>This method creates a synchronized collection and stores 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.</p> <p> <table> <tr><th>If you are using</th><th>consider using</th></tr> <tr><td>java.util.Vector</td><td>java.util.ArrayList</td></tr> <tr><td>java.util.Hashtable</td><td>java.util.HashMap</td></tr> <tr><td>java.lang.StringBuffer</td><td>java.lang.StringBuilder</td></tr> </table> </p> ]]> </Details> </BugPattern> <BugPattern type="FCBL_FIELD_COULD_BE_LOCAL"> <ShortDescription>Class defines fields that are used only as locals</ShortDescription> <LongDescription>Class {0} defines fields that are used only as locals</LongDescription> <Details> <![CDATA[ <p>This class defines fields that are used in a local 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.</p> ]]> </Details> </BugPattern> <BugPattern type="NOS_NON_OWNED_SYNCHRONIZATION"> <ShortDescription>Class uses non owned variables to synchronize on</ShortDescription> <LongDescription>Class {0} uses non owned variables to synchronize on</LongDescription> <Details> <![CDATA[ <p>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 their 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.</p> ]]> </Details> </BugPattern> <BugPattern type="NRTL_NON_RECYCLEABLE_TAG_LIB"> <ShortDescription>Tag library is not recycleable</ShortDescription> <LongDescription>Tag library {0} is not recycleable</LongDescription> <Details> <![CDATA[ <p>This tag library class implements an attribute whose associated backing store field is modified at another point in the tag library. In order for a tag library 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.</p> ]]> </Details> </BugPattern> <BugPattern type="S508C_NULL_LAYOUT"> <ShortDescription>GUI uses absolute layout</ShortDescription> <LongDescription>GUI {0} uses absolute layout</LongDescription> <Details> <![CDATA[ <p>This class passes null to <code>setLayout</code>, 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.</p> ]]> </Details> </BugPattern> <BugPattern type="S508C_NO_SETLABELFOR"> <ShortDescription>JLabel doesn't specify what it's labeling</ShortDescription> <LongDescription>JLabel in method {1} doesn't specify what it's labeling</LongDescription> <Details> <![CDATA[ <p>This class uses JLabels that do not specify what fields are being labeled. This hampers screen readers from giving appropriate feedback to users. Use the JLabel.setLabelFor method to accomplish this.</p> ]]> </Details> </BugPattern> <BugPattern type="S508C_NO_SETSIZE"> <ShortDescription>Window sets size manually, and doesn't use pack</ShortDescription> <LongDescription>Window {0} sets size manually, and doesn't use pack</LongDescription> <Details> <![CDATA[ <p>This class creates a window, and sizes the window using setSize. It is better, for handling font size changes, to use the pack method.</p> ]]> </Details> </BugPattern> <BugPattern type="S508C_NON_ACCESSIBLE_JCOMPONENT"> <ShortDescription>Class extends JComponent but does not implement Accessible interface</ShortDescription> <LongDescription>Class {0} extends JComponent but does not implement Accessible interface</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="S508C_SET_COMP_COLOR"> <ShortDescription>Method explicitly sets the color of a Component</ShortDescription> <LongDescription>Method {1} Method explicitly sets the color of a Component</LongDescription> <Details> <![CDATA[ <p>This method sets a Component's explicit foreground or background color which may cause difficulty for people with vision problems using this application. Colors should be allowed to be set from the operating system.</p> ]]> </Details> </BugPattern> <BugPattern type="S508C_NON_TRANSLATABLE_STRING"> <ShortDescription>Method passes constant string to title/label of component</ShortDescription> <LongDescription>Method {1} passes constant string to title/label of component</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="S508C_APPENDED_STRING"> <ShortDescription>Method passes appended string to title/label of component</ShortDescription> <LongDescription>Method {1} passes appended string to title/label of component</LongDescription> <Details> <![CDATA[ <p>This method creates a component and passes a string that was built up from a number of strings through appending multiple strings together. As foreign languages may order phrases differently, this will make translations difficult.</p> ]]> </Details> </BugPattern> <BugPattern type="UEC_USE_ENUM_COLLECTIONS"> <ShortDescription>Class uses an ordinary set or map with an enum class as the key</ShortDescription> <LongDescription>Class {0} uses an ordinary set or map with an enum class as the key</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SIL_SQL_IN_LOOP"> <ShortDescription>Method executes SQL queries inside of loops</ShortDescription> <LongDescription>Method {1} executes SQL queries inside of loops</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="NMCS_NEEDLESS_MEMBER_COLLECTION_SYNCHRONIZATION"> <ShortDescription>Class defines unneeded synchronization on member collection</ShortDescription> <LongDescription>Class {0} defines unneeded synchronization on member collection</LongDescription> <Details> <![CDATA[ <p>This class defines a private collection member as synchronized. It appears, however, that this collection is 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.</p> ]]> </Details> </BugPattern> <BugPattern type="ITC_INHERITANCE_TYPE_CHECKING"> <ShortDescription>Method uses instanceof on multiple types to arbitrate logic</ShortDescription> <LongDescription>Method {1} uses instanceof on multiple types to arbitrate logic</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SACM_STATIC_ARRAY_CREATED_IN_METHOD"> <ShortDescription>Method creates array using constants</ShortDescription> <LongDescription>Method {1} creates array using constants</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS"> <ShortDescription>Method appears to call the same method on the same object redundantly</ShortDescription> <LongDescription>Method {1} appears to call the same method on the same object redundantly</LongDescription> <Details> <![CDATA[ <p>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 variable, and using the variable the second time.</p> ]]> </Details> </BugPattern> <BugPattern type="UTA_USE_TO_ARRAY"> <ShortDescription>Method manually creates array from collection</ShortDescription> <LongDescription>Method {1} manually creates array from collection</LongDescription> <Details> <![CDATA[ <p>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 Collection method toArray. Given a collection 'mycollection' of type T, use <code>mycollection.toArray(new T[mycollection.size()]);</code></p> ]]> </Details> </BugPattern> <BugPattern type="LEST_LOST_EXCEPTION_STACK_TRACE"> <ShortDescription>Method throws alternative exception from catch block without history</ShortDescription> <LongDescription>Method {1} throws alternative exception from catch block without history</LongDescription> <Details> <![CDATA[ <p>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. If this exception has no constructor that takes an initial cause parameter, use the initCause method to initialize it instead.</p> <p> <pre><code> catch (IOException e) { throw new MySpecialException("Failed to open configuration", e); } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="UCPM_USE_CHARACTER_PARAMETERIZED_METHOD"> <ShortDescription>Method passes constant String of length 1 to character overridden method</ShortDescription> <LongDescription>Method {1} passes constant String of length 1 to character overridden method</LongDescription> <Details> <![CDATA[ <p>This method passes a constant literal <code>String</code> of length 1 as a parameter to a method, when a similar method is exposed that takes a <code>char</code>. It is simpler and more expedient to handle one character, rather than a <code>String</code>.</p> <p> Instead of making calls like: <br/> <pre><code> 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"); } </code></pre> Replace the single letter <code>String</code>s with their <code>char</code> equivalents like so:<br/> <pre><code> 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'); } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="TR_TAIL_RECURSION"> <ShortDescription>Method employs tail recursion</ShortDescription> <LongDescription>Method {1} employs tail recursion</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="URV_UNRELATED_RETURN_VALUES"> <ShortDescription>Method returns different types of unrelated Objects</ShortDescription> <LongDescription>Method {1} returns different types of unrelated Objects</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="URV_CHANGE_RETURN_TYPE"> <ShortDescription>Method returns more specific type of object than declared</ShortDescription> <LongDescription>Method {1} returns more specific type of object than declared</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="URV_INHERITED_METHOD_WITH_RELATED_TYPES"> <ShortDescription>Inherited method returns more specific type of object than declared</ShortDescription> <LongDescription>Inherited method {1} returns more specific type of object than declared</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="PIS_POSSIBLE_INCOMPLETE_SERIALIZATION"> <ShortDescription>Class doesn't serialize superclass fields</ShortDescription> <LongDescription>Class {0} doesn't serialize superclass fields</LongDescription> <Details> <![CDATA[ <p>This method implements Serializable but is derived from a class that does not. The superclass 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.</p> ]]> </Details> </BugPattern> <BugPattern type="SCRV_SUSPICIOUS_COMPARATOR_RETURN_VALUES"> <ShortDescription>Comparator method doesn't seem to return all ordering values</ShortDescription> <LongDescription>Comparator method {1} doesn't seem to return all ordering values</LongDescription> <Details> <![CDATA[ <p>This compareTo or compare method returns constant values to represent less than, equals, and greater than. However, it does not return each type, or it unconditionally returns a non zero value. Given that comparators are transitive, this seems incorrect.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_NEGATIVE_BITSET_ITEM"> <ShortDescription>Method passes a negative number as a bit to a BitSet which isn't supported</ShortDescription> <LongDescription>Method {1} passes a negative number as a bit to a BitSet which isn't supported</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_INTERN_ON_CONSTANT"> <ShortDescription>Method calls intern on a string constant</ShortDescription> <LongDescription>Method {1} calls intern on a string constant</LongDescription> <Details> <![CDATA[ <p>This method calls <code>intern</code> on a constant string. As constant strings are already interned, this call is superfluous.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_NO_CHAR_SB_CTOR"> <ShortDescription>Method appears to pass character to StringBuffer or StringBuilder integer constructor</ShortDescription> <LongDescription>Method {1} appears to pass character to StringBuffer or StringBuilder integer constructor</LongDescription> <Details> <![CDATA[ <p>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 the 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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_MATH_CONSTANT"> <ShortDescription>Method uses non-standard math constant</ShortDescription> <LongDescription>Method {1} uses non-standard math constant</LongDescription> <Details> <![CDATA[ <p>This method defines its own version of <em>PI</em> or <em>e</em> and the value is not as precise as the one defined in the constants Math.PI or Math.E. Use these constants instead.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_STUTTERED_ASSIGNMENT"> <ShortDescription>Method assigns a value to a local twice in a row</ShortDescription> <LongDescription>Method {1} assigns a value to a local twice in a row</LongDescription> <Details> <![CDATA[ <p>This method assigns a value twice in a row in a stuttered way such as <code>a = a = 5;</code> This is most probably a cut and paste error where the duplicate assignment can be removed.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_ISNAN"> <ShortDescription>Method incorrectly compares a floating point number to NaN</ShortDescription> <LongDescription>Method {1} compares a {3} to {4}.NaN</LongDescription> <Details> <![CDATA[ <p>This method compares a double or float to the constant <code>Double.NaN</code> or <code>Float.NaN</code>. You should use <code>Double.isNaN(d)</code> or <code>Float.isNaN(f)</code> if the variable is a primitive. If using a boxed primitive <code>d.isNaN()</code> or <code>f.isNaN()</code> should be used.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_BIGDECIMAL_STRING_CTOR"> <ShortDescription>Method passes double value to BigDecimal Constructor</ShortDescription> <LongDescription>Method {1} passes double value to BigDecimal Constructor</LongDescription> <Details> <![CDATA[ <p>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. </p> ]]> </Details> </BugPattern> <BugPattern type="SPP_STRINGBUFFER_WITH_EMPTY_STRING"> <ShortDescription>Method passes an empty string to StringBuffer of StringBuilder constructor</ShortDescription> <LongDescription>Method {1} passes an empty string to StringBuffer of StringBuilder constructor</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_INVALID_BOOLEAN_NULL_CHECK"> <ShortDescription>Method uses invalid C++ style null check on Boolean</ShortDescription> <LongDescription>Method {1} uses invalid C++ style null check on Boolean</LongDescription> <Details> <![CDATA[ <p>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. <pre><code> if (b && b.booleanValue()) </code></pre> should be<br/> <pre><code> if (Boolean.TRUE.equals(b)) </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_CHARAT"> <ShortDescription>Method fetches character array just to do the equivalent of the charAt method</ShortDescription> <LongDescription>Method {1} fetches character array just to do the equivalent of the charAt method</LongDescription> <Details> <![CDATA[ <p>This method calls the toCharArray method on a String to fetch an array of characters, only to retrieve one of those characters by index. It is more performant to just use the charAt method.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USELESS_TERNARY"> <ShortDescription>Method uses a ternary operator to cast a boolean to true or false</ShortDescription> <LongDescription>Method {1} uses a ternary operator to cast a boolean to true or false</LongDescription> <Details> <![CDATA[ <p>This method tests the value of a boolean and uses a ternary operator to return either true or false. The ternary operator is completely unnecessary, just use the original boolean value.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_SUSPECT_STRING_TEST"> <ShortDescription>Method possibly mixes up normal strings and empty strings in branching logic</ShortDescription> <LongDescription>Method {1} treats null and normal strings the same, when it should probably treat null and empty strings the same</LongDescription> <Details> <![CDATA[ <p>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: <br/> <pre><code> 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. } </code></pre> 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.</p> <p>Pattern found is one of the following: <ul> <li><code>if ((s == null) || (s.length() > 0))</code> --- did you mean <code>((s == null) || (s.length() == 0))</code>?</li> <li><code>if ((s == null) || (s.length() != 0))</code> -- did you mean <code>((s == null) || (s.length() == 0))</code>? </li> <li><code>if ((s != null) && (s.length() == 0))</code> -- did you mean <code>((s != null) && (s.length() > 0))</code> or perhaps <code>((s == null) || (s.length() == 0))</code>? </li> </ul> </p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_STRINGBUILDER_LENGTH"> <ShortDescription>Method converts StringBuffer or Builder to String just to get its length</ShortDescription> <LongDescription>Method {1} converts StringBuffer or Builder to String just to get its length</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_INVALID_CALENDAR_COMPARE"> <ShortDescription>Method passes a non calendar object to Calendar.before or Calendar.after</ShortDescription> <LongDescription>Method {1} passes a non calendar object to Calendar.before or Calendar.after</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_ZERO_WITH_COMPARATOR"> <ShortDescription>Method compares the result of a compareTo method to a value other than zero</ShortDescription> <LongDescription>Method {1} compares the result of a compareTo method to a value other than zero</LongDescription> <Details> <![CDATA[ This method calls the compareTo method on an object and then compares the resultant value to a value other than zero. The compareTo method is really only specified to return 0, a positive number or a negative number, so you should compare as == 0, or > 0 or < 0, and not to a specific value like == 1. ]]> </Details> </BugPattern> <BugPattern type="SPP_PASSING_THIS_AS_PARM"> <ShortDescription>Method call passes object that the method is called on as a parameter</ShortDescription> <LongDescription>Method call in {1} passes object that the method is called on as a parameter</LongDescription> <Details> <![CDATA[ <p>This method calls an instance method passing the object that the method is called on as a parameter, such as <code> foo.someMethod(foo); </code> As you already have access to this object thru this, you don't need to pass it. </p> ]]> </Details> </BugPattern> <BugPattern type="MUI_USE_CONTAINSKEY"> <ShortDescription>Method calls keySet() just to call contains, use containsKey instead</ShortDescription> <LongDescription>Method {1} calls keySet() just to call contains, use containsKey instead</LongDescription> <Details> <![CDATA[ <p>This method calls mySet.keySet().contains("foo") when mySet.containsKey("foo") is simpler.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_ISEMPTY"> <ShortDescription>Method checks the size of a collection against zero rather than using isEmpty()</ShortDescription> <LongDescription>Method {1} checks the size of a collection against zero rather than using isEmpty()</LongDescription> <Details> <![CDATA[ <p>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().</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_GETPROPERTY"> <ShortDescription>Method calls getProperties just to get one property, use getProperty instead</ShortDescription> <LongDescription>Method {1} calls getProperties just to get one property, use getProperty instead</LongDescription> <Details> <![CDATA[ <table> <tr><td>This method uses</td></tr> <tr><td>String prop = System.getProperties().getProperty("foo");</td></tr> <tr><td>instead of simply using</td></tr> <tr><td>String prop = System.getProperty("foo");</td></tr> </table> ]]> </Details> </BugPattern> <BugPattern type="SPP_SERIALVER_SHOULD_BE_PRIVATE"> <ShortDescription>Class defines a serialVersionUID as non private</ShortDescription> <LongDescription>Class {0} defines a serialVersionUID as non private</LongDescription> <Details> <![CDATA[ <p>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 affect any derived classes, defining it as non private is confusing. It is suggested you change this variable to be private.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USELESS_CASING"> <ShortDescription>Method compares string without case after enforcing a case</ShortDescription> <LongDescription>Method {1} compares string without case after enforcing a case</LongDescription> <Details> <![CDATA[ <p>This method compares two strings with compareToIgnoreCase or equalsIgnoreCase, after having called toUpperCase or toLowerCase on the strings in question. As you are comparing without concern for case, the toUpperCase or toLowerCase calls are pointless and can be removed.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_NON_ARRAY_PARM"> <ShortDescription>Method passes a non array object to a parameter that expects an array</ShortDescription> <LongDescription>Method {1} passes a non array object to a parameter that expects an array</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_EMPTY_CASING"> <ShortDescription>Method passes an empty string to equalsIgnoreCase or compareToIgnoreCase</ShortDescription> <LongDescription>Method {1} passes an empty string to equalsIgnoreCase or compareToIgnoreCase</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_TEMPORARY_TRIM"> <ShortDescription>Method trims a String temporarily</ShortDescription> <LongDescription>Method {1} trims a String temporarily</LongDescription> <Details> <![CDATA[ <p>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 probably should be trimmed when you actually 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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_STRINGBUILDER_IS_MUTABLE"> <ShortDescription>Method needlessly assigns a StringBuilder to itself, as it's mutable</ShortDescription> <LongDescription>Method {1} needlessly assigns a StringBuilder to itself, as it's mutable</LongDescription> <Details> <![CDATA[ <p>This method calls StringBuilder.append and assigns the results to the same StringBuilder like:</p> <code>sb = sb.append("foo")</code> <p>StringBuilder is mutable, so this is not necessary. This is also true of StringBuffer.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_USE_GET0"> <ShortDescription>Method uses iterator().next() on a List to get the first item</ShortDescription> <LongDescription>Method {1} uses iterator().next() on a List to get the first item</LongDescription> <Details> <![CDATA[ <p>This method calls myList.iterator().next() on a List to get the first item. It is more performant to just use myList.get(0).</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_DOUBLE_APPENDED_LITERALS"> <ShortDescription>Method appends two literal strings back to back to a StringBuilder</ShortDescription> <LongDescription>Method {1} appends two literal strings back to back to a StringBuilder</LongDescription> <Details> <![CDATA[ <p>This method appends two literal strings to a <code>StringBuilder</code> back to back. Modern compilers will optimize something like:<br/> <pre><code> public static final string CONST_VAL = "there"; ... String str = "Hello" + " "+ CONST_VAL + " " +"world!"; </code></pre> to: <br/> <pre><code> public static final string CONST_VAL = "there"; ... String str = "Hello there world!"; </code></pre> This means the concatenation is done during compile time, not at runtime, so there's <b>no need</b> to do: <br/> <pre><code> public static final string CONST_VAL = "there"; ... StringBuilder sb = new StringBuilder("Hello").append(" ").append(CONST_VAL).append(" ").append("world!"); String str = sb.toString(); </code></pre> which is harder to read and will result in more complex bytecode. </p> <p> Simply append your constants with the "+" symbol, don't append them with <code>StringBuilder.append()</code>. </p> ]]> </Details> </BugPattern> <BugPattern type="SPP_NULL_BEFORE_INSTANCEOF"> <ShortDescription>Method checks a reference for null before calling instanceof</ShortDescription> <LongDescription>Method {1} checks a reference for null before calling instanceof</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_NON_USEFUL_TOSTRING"> <ShortDescription>Method calls toString() on an instance of a class that hasn't overridden toString()</ShortDescription> <LongDescription>Method {1} calls toString() on an instance of a class that hasn't overridden toString()</LongDescription> <Details> <![CDATA[ <p>This method calls <code>toString</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_TOSTRING_ON_STRING"> <ShortDescription>Method calls toString() on a String</ShortDescription> <LongDescription>Method {1} calls toString() on a String</LongDescription> <Details> <![CDATA[ <p>This method calls <code>toString</code> on a String. Just use the object itself if you want a String.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_CONVERSION_OF_STRING_LITERAL"> <ShortDescription>Method converts a String literal</ShortDescription> <LongDescription>Method {1} calls {3} on a String Literal</LongDescription> <Details> <![CDATA[ <p>This method calls a converting method like <code>toLowerCase</code> or <code>trim</code> on a <code>String</code> literal. You should make the transformation yourself and use the transformed literal.</p> <p> For example, instead of :<br/> <pre><code> return "ThisIsAConstantString".toLowerCase().trim(); </code></pre> just do <br/> <pre><code> return "thisisaconstantstring"; </code></pre> for shorter and easier to read code. An exception might be made when locale-specific transformations need to be done (in the case of <code>toUpperCase()</code> and <code>toLowerCase()</code>. </p> ]]> </Details> </BugPattern> <BugPattern type="SPP_EQUALS_ON_STRING_BUILDER"> <ShortDescription>Method calls equals(Object o) on a StringBuilder or StringBuffer</ShortDescription> <LongDescription>Method {1} calls equals(Object o) on a StringBuilder or StringBuffer</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_STATIC_FORMAT_STRING"> <ShortDescription>Method calls String.format on a static (non parameterized) format string</ShortDescription> <LongDescription>Method {1} calls String.format on a static (non parameterized) format string</LongDescription> <Details> <![CDATA[ <p>This method calls String.format, passing a static string that has no replacement markers (starting with %) as the format string. 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.</p> ]]> </Details> </BugPattern> <BugPattern type="SPP_WRONG_COMMONS_TO_STRING_OBJECT"> <ShortDescription>Method does not pass an object to commons-lang's ToStringBuilder</ShortDescription> <LongDescription>Method {1} does not pass an object to commons-lang's ToStringBuilder</LongDescription> <Details> <![CDATA[ This method uses commons-lang, or commons-lang3's ToStringBuilder to attempt to output a representation of an object. However, no object was passed, just the style specifier, and so the output will be of the ToStringStyle object itself. Don't forget to include the object you wish to output as the first parameter, such as <pre> ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); </pre> ]]> </Details> </BugPattern> <BugPattern type="MUI_NULL_CHECK_ON_MAP_SUBSET_ACCESSOR"> <ShortDescription>Method checks whether the keySet(), entrySet() or values() collection of a Map is null</ShortDescription> <LongDescription>Method {1} checks whether the keySet(), entrySet() or values() collection of a Map is null</LongDescription> <Details> <![CDATA[ This method checks to see if the return value from a keySet(), entrySet() or values() method call on a Map is null. For any valid functioning Map these collections will always be non-null, and so the call is superfluous. Maybe you intended to check whether those sets were empty instead. ]]> </Details> </BugPattern> <BugPattern type="BAS_BLOATED_ASSIGNMENT_SCOPE"> <ShortDescription>Method assigns a variable in a larger scope than is needed</ShortDescription> <LongDescription>Method {1} assigns a variable in a larger scope than is needed</LongDescription> <Details> <![CDATA[ <p><em>THIS DETECTOR IS HIGHLY EXPERIMENTAL AND IS LIKELY TO CREATE A LOT OF FUD</em></p> <p>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 <code>if</code> 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, and that changes are not made further down that will affect the execution of the assignment when done later on.</p> ]]> </Details> </BugPattern> <BugPattern type="SCII_SPOILED_CHILD_INTERFACE_IMPLEMENTOR"> <ShortDescription>Class implements interface by relying on unknowing superclass methods</ShortDescription> <LongDescription>Class {0} implements interface by relying on unknowing superclass methods</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="DWI_DELETING_WHILE_ITERATING"> <ShortDescription>Method deletes collection element while iterating</ShortDescription> <LongDescription>Method {1} deletes collection element while iterating</LongDescription> <Details> <![CDATA[ <p>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 ConcurrentModificationException to be thrown. To avoid this, the remove method of the iterator should be used.</p> ]]> </Details> </BugPattern> <BugPattern type="DWI_MODIFYING_WHILE_ITERATING"> <ShortDescription>Method modifies collection element while iterating</ShortDescription> <LongDescription>Method {1} modifies collection element while iterating</LongDescription> <Details> <![CDATA[ <p>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 ConcurrentModificationException to be thrown.</p> ]]> </Details> </BugPattern> <BugPattern type="USS_USE_STRING_SPLIT"> <ShortDescription>Method builds String array using String Tokenizing</ShortDescription> <LongDescription>Method {1} builds String array using String Tokenizing</LongDescription> <Details> <![CDATA[ <p>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.</p> <p>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:</p> <pre><code> if (s.length() > 0) <br/> return s.split(";");<br/> return new String[0];<br/> </code></pre> ]]> </Details> </BugPattern> <BugPattern type="SJVU_SUSPICIOUS_JDK_VERSION_USE"> <ShortDescription>Method uses rt.jar class or method that does not exist</ShortDescription> <LongDescription>Method {1} uses rt.jar class or method that does not exist for the version the class is compiled for</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="UAA_USE_ADD_ALL"> <ShortDescription>Method uses simple loop to copy contents of one collection to another</ShortDescription> <LongDescription>Method {1} uses simple loop to copy contents of one collection to another</LongDescription> <Details> <![CDATA[ <p>This method uses a simple <code>for</code> loop to copy the contents of a set, list, map key/value, array or other collection to another collection. It is simpler and more straightforward 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 the Arrays.asList method to wrap the array into a collection.</p> ]]> </Details> </BugPattern> <BugPattern type="MRC_METHOD_RETURNS_CONSTANT"> <ShortDescription>Private or static method only returns one constant value</ShortDescription> <LongDescription>Private or static method {1} only returns one constant value</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="NCS_NEEDLESS_CUSTOM_SERIALIZATION"> <ShortDescription>Method needlessly implements what is default streaming behavior</ShortDescription> <LongDescription>Method {1} needlessly implements what is default streaming behavior</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="MOM_MISLEADING_OVERLOAD_MODEL"> <ShortDescription>Class 'overloads' a method with both instance and static versions</ShortDescription> <LongDescription>Class {0} 'overloads' a method with both instance and static versions</LongDescription> <Details> <![CDATA[ <p>This class 'overloads' the same method with both instance and static versions. As the use of these two models is different, it will be confusing to the users of these methods.</p> ]]> </Details> </BugPattern> <BugPattern type="EXS_EXCEPTION_SOFTENING_NO_CONSTRAINTS"> <ShortDescription>Unconstrained method converts checked exception to unchecked</ShortDescription> <LongDescription>Unconstrained method {1} converts checked exception to unchecked</LongDescription> <Details> <![CDATA[ <p>This method is not constrained by an interface or superclass, but converts a caught checked exception to an unchecked exception and throws it. It would be more appropriate just to throw the checked exception, adding the exception to the throws clause of the method.</p> ]]> </Details> </BugPattern> <BugPattern type="EXS_EXCEPTION_SOFTENING_HAS_CHECKED"> <ShortDescription>Constrained method converts checked exception to unchecked instead of another allowable checked exception</ShortDescription> <LongDescription>Constrained method {1} converts checked exception to unchecked instead of another allowable checked exception</LongDescription> <Details> <![CDATA[ <p>This method's exception signature is constrained by an interface of superclass not to 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.</p> ]]> </Details> </BugPattern> <BugPattern type="EXS_EXCEPTION_SOFTENING_NO_CHECKED"> <ShortDescription>Constrained method converts checked exception to unchecked</ShortDescription> <LongDescription>Constrained method {1} converts checked exception to unchecked</LongDescription> <Details> <![CDATA[ <p>This method's exception signature is constrained by an interface or superclass not to 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 changing the signature of this method to include the checked exception.</p> ]]> </Details> </BugPattern> <BugPattern type="EXS_EXCEPTION_SOFTENING_RETURN_FALSE"> <ShortDescription>method converts an exception into a boolean 'error code' value</ShortDescription> <LongDescription>method {1} converts an exception into a boolean 'error code' value</LongDescription> <Details> <![CDATA[ <p>This method catches an 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.</p> ]]> </Details> </BugPattern> <BugPattern type="CFS_CONFUSING_FUNCTION_SEMANTICS"> <ShortDescription>Method returns modified parameter</ShortDescription> <LongDescription>Method {1} returns modified parameter</LongDescription> <Details> <![CDATA[ <p>This method appears to modify a parameter, and then return this parameter as the method's 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 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.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_ACTUAL_CONSTANT"> <ShortDescription>JUnit test method passes constant to second (actual) assertion parameter</ShortDescription> <LongDescription>JUnit test method {1} passes constant to second (actual) assertion parameter</LongDescription> <Details> <![CDATA[ <p>This method calls <code>assertXXX</code> passing a constant value as the second of the two values. The assert methods assume that the expected value is the first parameter, and so it appears that the order of values has been swapped here.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_INEXACT_DOUBLE"> <ShortDescription>JUnit test method asserts that two doubles are exactly equal</ShortDescription> <LongDescription>JUnit test method {1} asserts that two doubles are exactly equal</LongDescription> <Details> <![CDATA[ <p>This method calls <code>assertXXX</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_BOOLEAN_ASSERT"> <ShortDescription>JUnit test method asserts that a value is equal to true or false</ShortDescription> <LongDescription>JUnit test method {1} asserts that a value is equal to true or false</LongDescription> <Details> <![CDATA[ <p>This method asserts that a value is equal to true or false. It is simpler to just use assertTrue or assertFalse instead.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_IMPOSSIBLE_NULL"> <ShortDescription>JUnit test method asserts that an autoboxed value is not null</ShortDescription> <LongDescription>JUnit test method {1} asserts that an autoboxed value is not null</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_ASSERT_USED"> <ShortDescription>JUnit test method uses Java asserts rather than a JUnit assertion</ShortDescription> <LongDescription>JUnit test method {1} uses Java asserts rather than a JUnit assertion</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_USE_ASSERT_NULL"> <ShortDescription>JUnit test method passes null Assert.assertEquals</ShortDescription> <LongDescription>JUnit test method {1} passes null to Assert.assertEquals</LongDescription> <Details> <![CDATA[ <p>This method compares an object's equality to null. It is better to use the Assert.assertNull method so that the JUnit failure method is more descriptive of the intended test.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_USE_ASSERT_NOT_NULL"> <ShortDescription>JUnit test method passes null Assert.assertNotEquals</ShortDescription> <LongDescription>JUnit test method {1} passes null to Assert.assertNotEquals</LongDescription> <Details> <![CDATA[ <p>This method compares an object's inequality to null. It is better to use the Assert.assertNotNull method so that the JUnit failure method is more descriptive of the intended test.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_USE_ASSERT_EQUALS"> <ShortDescription>JUnit test method passes boolean expression to Assert.assertFalse / Assert.assertTrue</ShortDescription> <LongDescription>JUnit test method {1} passes boolean expression to Assert.assertFalse / Assert.assertTrue</LongDescription> <Details> <![CDATA[ <p>This method evaluates a boolean expression and passes that to Assert.assertFalse / 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 descriptive of the intended test.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_USE_ASSERT_NOT_EQUALS"> <ShortDescription>JUnit test method passes boolean expression to Assert.assertFalse / Assert.assertTrue</ShortDescription> <LongDescription>JUnit test method {1} passes boolean expression to Assert.assertFalse / Assert.assertTrue</LongDescription> <Details> <![CDATA[ <p>This method evaluates a boolean expression and passes that to Assert.assertFalse / Assert.assertTrue. It is better to pass the two values that are being equated to the Assert.assertNotEquals method so that the JUnit failure method is more descriptive of the intended test.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_NO_ASSERT"> <ShortDescription>JUnit test method appears to have no assertions</ShortDescription> <LongDescription>JUnit test method {1} appears to have no assertions</LongDescription> <Details> <![CDATA[ <p>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. Consider calling <code>fail</code> after an exception was expected. 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.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_JUNIT_ASSERTION_ODDITIES_USING_DEPRECATED"> <ShortDescription>JUnit 4 test using deprecated junit.framework.* classes</ShortDescription> <LongDescription>JUnit 4 test {1} using deprecated junit.framework.* classes</LongDescription> <Details> <![CDATA[ <p>This JUnit 4 test is still using classes from the junit.framework.* package. You should switch them over to the corresponding org.junit.* set of classes, instead.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_ACTUAL_CONSTANT"> <ShortDescription>TestNG test method passes constant to first (actual) assertion parameter</ShortDescription> <LongDescription>TestNG test method {1} passes constant to first (actual) assertion parameter</LongDescription> <Details> <![CDATA[ <p>This method calls <code>assertXXX</code> passing a constant value as the first of the two values. The assert method assumes that the expected value is the second parameter, and so it appears that the order of values has been swapped here.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_INEXACT_DOUBLE"> <ShortDescription>TestNG test method asserts that two doubles are exactly equal</ShortDescription> <LongDescription>TestNG test method {1} asserts that two doubles are exactly equal</LongDescription> <Details> <![CDATA[ <p>This method calls <code>assertXXX</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_BOOLEAN_ASSERT"> <ShortDescription>TestNG test method asserts that a value is true or false</ShortDescription> <LongDescription>TestNG test method {1} asserts that a value is true or false</LongDescription> <Details> <![CDATA[ <p>This method asserts that a value is equal to true or false. It is simpler to just use assertTrue, or assertFalse, instead.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_IMPOSSIBLE_NULL"> <ShortDescription>TestNG test method asserts that an autoboxed value is not null</ShortDescription> <LongDescription>TestNG test method {1} asserts that an autoboxed value is not null</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_ASSERT_USED"> <ShortDescription>TestNG test method uses Java asserts rather than a TestNG assertion</ShortDescription> <LongDescription>TestNG test method {1} uses Java asserts rather than a TestNG assertion</LongDescription> <Details> <![CDATA[ <p>This method uses a Java assert to assure that a certain state is in effect. As this is a TestNG test it makes more sense to either check this condition with a TestNG assert, or allow a following exception to occur.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_USE_ASSERT_NULL"> <ShortDescription>TestNG test method passes null Assert.assertEquals</ShortDescription> <LongDescription>TestNG test method {1} passes null to Assert.assertEquals</LongDescription> <Details> <![CDATA[ <p>This method compares an object's equality to null. It is better to use the Assert.assertNull method so that the TestNG failure method is more descriptive of the intended test.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_USE_ASSERT_NOT_NULL"> <ShortDescription>TestNG test method passes null Assert.assertNotEquals</ShortDescription> <LongDescription>TestNG test method {1} passes null to Assert.assertNotEquals</LongDescription> <Details> <![CDATA[ <p>This method compares an object's inequality to null. It is better to use the Assert.assertNotNull method so that the TestNG failure method is more descriptive of the intended test.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_USE_ASSERT_EQUALS"> <ShortDescription>TestNG test method passes boolean expression to Assert.assertFalse / Assert.assertTrue</ShortDescription> <LongDescription>TestNG test method {1} passes boolean expression to Assert.assertFalse / Assert.assertTrue</LongDescription> <Details> <![CDATA[ <p>This method evaluates a boolean expression and passes that to Assert.assertFalse / Assert.assertTrue. It is better to pass the two values that are being equated to the Assert.assertEquals method so that the TestNG failure method is more meaningful of the intended test.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_USE_ASSERT_NOT_EQUALS"> <ShortDescription>TestNG test method passes boolean expression to Assert.assertFalse / Assert.assertTrue</ShortDescription> <LongDescription>TestNG test method {1} passes boolean expression to Assert.assertFalse / Assert.assertTrue</LongDescription> <Details> <![CDATA[ <p>This method evaluates a boolean expression and passes that to Assert.assertFalse / Assert.assertTrue. It is better to pass the two values that are being equated to the Assert.assertNotEquals method so that the TestNG failure method is more meaningful of the intended test.</p> ]]> </Details> </BugPattern> <BugPattern type="UTAO_TESTNG_ASSERTION_ODDITIES_NO_ASSERT"> <ShortDescription>TestNG test method appears to have no assertions</ShortDescription> <LongDescription>TestNG test method {1} appears to have no assertions</LongDescription> <Details> <![CDATA[ <p>This TestNG 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. Consider calling <code>fail</code> after an exception was expected. 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.</p> ]]> </Details> </BugPattern> <BugPattern type="SCA_SUSPICIOUS_CLONE_ALGORITHM"> <ShortDescription>Clone method stores a new value to member field of source object</ShortDescription> <LongDescription>Clone method {1} stores a new value to member field of source object</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="WEM_WEAK_EXCEPTION_MESSAGING"> <ShortDescription>Method throws exception with static message string</ShortDescription> <LongDescription>Method {1} throws exception with static message string</LongDescription> <Details> <![CDATA[ <p>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 values 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.</p> ]]> </Details> </BugPattern> <BugPattern type="WEM_OBSCURING_EXCEPTION"> <ShortDescription>Method throws a java.lang.Exception that wraps a more useful exception</ShortDescription> <LongDescription>Method {1} throws a java.lang.Exception that wraps a more useful exception</LongDescription> <Details> <![CDATA[ <p>This method catches an exception and generates a new exception of type java.lang.Exception, passing the original exception as the new Exception's cause. If the original Exception was actually a java.lang.Error, this is dubious as you should not be handling errors. If the original exception is a more specific exception, there is no reason to wrap it in a java.lang.Exception; this just obfuscates the type of error that is occurring. </p> ]]> </Details> </BugPattern> <BugPattern type="SCSS_SUSPICIOUS_CLUSTERED_SESSION_SUPPORT"> <ShortDescription>Method modifies an http session attribute without calling setAttribute</ShortDescription> <LongDescription>Method {1} modifies an http session attribute without calling setAttribute</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="LO_LOGGER_LOST_EXCEPTION_STACK_TRACE"> <ShortDescription>Method incorrectly passes exception as first argument to logger method</ShortDescription> <LongDescription>Method {1} incorrectly passes exception as first argument to logger method</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="LO_SUSPECT_LOG_CLASS"> <ShortDescription>Method specifies an unrelated class when allocating a Logger</ShortDescription> <LongDescription>Method {1} specifies an unrelated class when allocating a Logger. Saw "{3}", expected "{4}".</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="LO_SUSPECT_LOG_PARAMETER"> <ShortDescription>Constructor declares a Logger parameter</ShortDescription> <LongDescription>Constructor {1} declares a Logger parameter</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="LO_STUTTERED_MESSAGE"> <ShortDescription>Method stutters exception message in logger</ShortDescription> <LongDescription>Method {1} stutters exception message in logger</LongDescription> <Details> <![CDATA[ <p>This method uses a logger method that takes an exception, and passes the result of the exception's getMessage() method 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 handwritten message that describes the error in this method, possibly including the values of key variables.</p> ]]> </Details> </BugPattern> <BugPattern type="LO_INVALID_FORMATTING_ANCHOR"> <ShortDescription>Method attempts to log using numbered formatting anchors</ShortDescription> <LongDescription>Method {1} attempts to log using numbered formatting anchors</LongDescription> <Details> <![CDATA[ <p>This method attempts to use an SLF4J or Log4j2 logger to log a parameterized expression using formatting anchors. However, SLF4J and Log4j2 use simple non numbered anchors such as {}, rather than anchors with digits in them as the code uses. Thus no parameter replacement will occur.</p> <p>This pattern is invalid: <code>LOGGER.error("{0} is broken", theThing);</code> Use instead <code>LOGGER.error("{} is broken", theThing);</code> </p> ]]> </Details> </BugPattern> <BugPattern type="LO_INVALID_STRING_FORMAT_NOTATION"> <ShortDescription>Method attempts to log using String.format notation</ShortDescription> <LongDescription>Method {1} attempts to log using String.format notation</LongDescription> <Details> <![CDATA[ <p>This method attempts to use an SLF4J or Log4j2 logger to log a parameterized expression using String.format notation. However, SLF4J and Log4j2 uses simple non numbered anchors such as {}, rather than anchors with percent signs in them as the code uses. Thus no parameter replacement will occur.</p> <p>This pattern is invalid: <code>LOGGER.error("%s is broken", theThing);</code> Use instead <code>LOGGER.error("{} is broken", theThing);</code> </p> ]]> </Details> </BugPattern> <BugPattern type="LO_INCORRECT_NUMBER_OF_ANCHOR_PARAMETERS"> <ShortDescription>Method passes an incorrect number of parameters to an SLF4J or Log4j2 logging statement</ShortDescription> <LongDescription>Method {1} passes an incorrect number of parameters to an SLF4J or Log4j2 logging statement</LongDescription> <Details> <![CDATA[ <p>This method passes the wrong number of parameters to an SLF4J or Log4j2 logging method (error, warn, info, debug) based on the number of anchors {} in the format string. An additional exception argument is allowed if found.</p> ]]> </Details> </BugPattern> <BugPattern type="LO_EXCEPTION_WITH_LOGGER_PARMS"> <ShortDescription>Method creates exception with logger parameter markers in message</ShortDescription> <LongDescription>Method {1} creates exception with logger parameter markers in message</LongDescription> <Details> <![CDATA[ <p>This method passes a standard exception as a logger parameter, and expects this exception to be substituted in an SLF4J or Log4j style parameter marker '{}'. This marker will not be translated as SLF4J and Log4j2 don't process the Exception class for markers. </p> ]]> </Details> </BugPattern> <BugPattern type="LO_APPENDED_STRING_IN_FORMAT_STRING"> <ShortDescription>Method passes a concatenated string to SLF4J's or Log4j2's format string</ShortDescription> <LongDescription>Method {1} passes a concatenated string to SLF4J's or Log4j2's format string</LongDescription> <Details> <![CDATA[ <p>This method uses an SLF4J or Log4j2 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.</p> ]]> </Details> </BugPattern> <BugPattern type="LO_EMBEDDED_SIMPLE_STRING_FORMAT_IN_FORMAT_STRING"> <ShortDescription>Method passes a simple String.format result to an SLF4J's or Log4j2's format string</ShortDescription> <LongDescription>Method {1} passes a simple String.format result to an SLF4J's or Log4j2's format string</LongDescription> <Details> <![CDATA[ <p>This method uses an SLF4J or Log4J2 logger to log a string which was produced through a call to String.format, where the format string passed was a constant string containing only simple format markers that could be directly handled by SLF4J or Log4J. Rather than doing <pre> logger.error(String.format("This %s is an error", s)); <pre> do <pre> logger.error("This {} is an error", s); </pre> </p> ]]> </Details> </BugPattern> <BugPattern type="LO_TOSTRING_PARAMETER"> <ShortDescription>Method explicitly calls toString() on a logger parameter</ShortDescription> <LongDescription>Method {1} explicitly calls toString() on a logger parameter</LongDescription> <Details> <![CDATA[ <p>This method uses parameterized logging to avoid the cost of string concatenation in the case that the log level does not meet the needed level. However, one or more of the parameters passed to the logging method uses .toString() to present a String representation for the parameter. This is unneeded as the logger will do this for you, and because it is explicitly done, will always be called even if the log statement is not actually written. Also, by dropping the '.toString()' you may avoid unnecessary NPEs. Just pass the variable as a parameter instead. ]]> </Details> </BugPattern> <BugPattern type="LO_NON_PRIVATE_STATIC_LOGGER"> <ShortDescription>Class defines non private logger using a static class context</ShortDescription> <LongDescription>Class {0} defines a non private logger using a static class context</LongDescription> <Details> <![CDATA[ <p>This class defines a static logger as non private. It does so by passing the name of a class such as <code><pre>public static final Logger LOG = LoggerFactory.getLogger(Foo.class);</pre></code> Since this class is public it may be used in other classes, but doing so will provide the incorrect class reference as the class is hard coded. </p> <p> It is recommend to define static loggers as private, and just redefine a new logger in any class that you need to have logging done. <p> <p>If you wish to have a base class define the logger, and have derived classes use that logger, you can potentially use instance based logging, such as <code><pre>protected final Logger LOG = LoggerFactory.getLogger(getClass());</pre></code> However this has the downside of being an instance based logger, and creating a logger object in each instance of the class where it is used. </p> ]]> </Details> </BugPattern> <BugPattern type="IICU_INCORRECT_INTERNAL_CLASS_USE"> <ShortDescription>Class relies on internal API classes</ShortDescription> <LongDescription>Class {0} relies on internal API classes</LongDescription> <Details> <![CDATA[ <p>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.</p> Packages that shouldn't be used are: <ul> <li>sun.xxx</li> <li>org.apache.xerces.xxx</li> <li>org.apache.xalan.xxx</li> </ul> ]]> </Details> </BugPattern> <BugPattern type="DSOC_DUBIOUS_SET_OF_COLLECTIONS"> <ShortDescription>Method uses a set of collections</ShortDescription> <LongDescription>Method {1} uses a set of collections</LongDescription> <Details> <![CDATA[ <p>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.</p> <p>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.</p> <p>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.</p> <p>If you wish to maintain a collection of collections, it is probably better to use a List as the outer collection.</p> ]]> </Details> </BugPattern> <BugPattern type="BED_BOGUS_EXCEPTION_DECLARATION"> <ShortDescription>Non derivable method declares throwing an exception that isn't thrown</ShortDescription> <LongDescription>Non derivable method {1} declares throwing an exception that isn't thrown</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="BED_HIERARCHICAL_EXCEPTION_DECLARATION"> <ShortDescription>Method declares throwing two or more exceptions related by inheritance</ShortDescription> <LongDescription>Method {1} declares throwing two or more exceptions related by inheritance</LongDescription> <Details> <![CDATA[ <p>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; it just adds confusion.</p> ]]> </Details> </BugPattern> <BugPattern type="UNNC_UNNECESSARY_NEW_NULL_CHECK"> <ShortDescription>Method checks the result of a new allocation</ShortDescription> <LongDescription>Method {1} checks the result of a new allocation</LongDescription> <Details> <![CDATA[ <p>This method allocates an object with <code>new</code>, 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.</p> ]]> </Details> </BugPattern> <BugPattern type="DTEP_DEPRECATED_TYPESAFE_ENUM_PATTERN"> <ShortDescription>Class appears to implement the old style type safe enum pattern</ShortDescription> <LongDescription>Class {0} appears to implement the old style type safe enum pattern</LongDescription> <Details> <![CDATA[ <p>This class appears to implement the old-style typesafe 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 <code>enum</code>.</p> ]]> </Details> </BugPattern> <BugPattern type="TBP_TRISTATE_BOOLEAN_PATTERN"> <ShortDescription>Method returns null for Boolean type</ShortDescription> <LongDescription>Method {1} returns null for Boolean type</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SUA_SUSPICIOUS_UNINITIALIZED_ARRAY"> <ShortDescription>Method returns an array that appears not to be initialized</ShortDescription> <LongDescription>Method {1} returns an array that appears not to be initialized</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="ITU_INAPPROPRIATE_TOSTRING_USE"> <ShortDescription>Method performs algorithmic operations on the result of a toString() call</ShortDescription> <LongDescription>Method {1} performs algorithmic operations on the result of a toString() call</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="IKNC_INCONSISTENT_HTTP_ATTRIBUTE_CASING"> <ShortDescription>Method uses the same HttpSession attribute name but with different casing</ShortDescription> <LongDescription>Method {1} uses the same HttpSession attribute name but with different casing</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="IKNC_INCONSISTENT_HTTP_PARAM_CASING"> <ShortDescription>Method uses the same HttpRequest parameter name but with different casing</ShortDescription> <LongDescription>Method {1} uses the same HttpRequest parameter name but with different casing</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="OC_OVERZEALOUS_CASTING"> <ShortDescription>Method manually casts the right hand side of an assignment more specifically than needed</ShortDescription> <LongDescription>Method {1} manually casts the right hand side of an assignment more specifically than needed</LongDescription> <Details> <![CDATA[ <p>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 the variable that is on the left. Using a more specific type on the right hand side just increases cohesion.</p> ]]> </Details> </BugPattern> <BugPattern type="PDP_POORLY_DEFINED_PARAMETER"> <ShortDescription>Method defines parameters more abstractly than needed to function properly</ShortDescription> <LongDescription>Method {1} defines parameters more abstractly than needed to function properly</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="NSE_NON_SYMMETRIC_EQUALS"> <ShortDescription>Equals method compares this object against other types in a non symmetric way</ShortDescription> <LongDescription>Equals method {1} compares this object against other types in a non symmetric way</LongDescription> <Details> <![CDATA[ <p>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.</p> <p> Here's an example of a BAD equals method, do NOT do this: <pre><code> class Person { public boolean equals(Object o) { if (o instanceof Person) { return name.equals(((Person) o).name); } else if (o instanceof String) { return name.equals(o); } return false; } } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="CVAA_CONTRAVARIANT_ARRAY_ASSIGNMENT"> <ShortDescription>Method performs a contravariant array assignment</ShortDescription> <LongDescription>Method {1} performs a contravariant array assignment</LongDescription> <Details> <![CDATA[ <p>This method contains a contravariant array assignment. Since arrays are mutable data structures, their use must be restricted to covariant or invariant usage.</p> <pre><code> class A {} class B extends A {} B[] b = new B[2]; A[] a = b; </code></pre> ]]> </Details> </BugPattern> <BugPattern type="CVAA_CONTRAVARIANT_ELEMENT_ASSIGNMENT"> <ShortDescription>Method performs a contravariant array element assignment</ShortDescription> <LongDescription>Method {1} performs a contravariant array element assignment</LongDescription> <Details> <![CDATA[ <p>This method contains a contravariant array element assignment. Since arrays are mutable data structures, their use must be restricted to covariant or invariant usage.</p> <pre><code> class A {} class B extends A {} B[] b = new B[2]; A[] a = b; a[0] = new A(); // results in ArrayStoreException (Runtime) </code></pre> ]]> </Details> </BugPattern> <BugPattern type="NFF_NON_FUNCTIONAL_FIELD"> <ShortDescription>Serializable class defines a final transient field</ShortDescription> <LongDescription>Serializable class {0} defines a final transient field</LongDescription> <Details> <![CDATA[ <p>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 deserializing, the field is not initialized. And since the field is final, no other method can initialize it either.</p> ]]> </Details> </BugPattern> <BugPattern type="SNG_SUSPICIOUS_NULL_FIELD_GUARD"> <ShortDescription>Method tests a field for not null as guard and reassigns it</ShortDescription> <LongDescription>Method {1} tests a field for not null as guard and reassigns it</LongDescription> <Details> <![CDATA[ <p>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.</p> <p>example: <pre><code> if (name != null) { name = person.getName(); } </code></pre> It is possible this is correct, but it seems likely the guard was meant to be <code>if (name == null)</code> </p> ]]> </Details> </BugPattern> <BugPattern type="SNG_SUSPICIOUS_NULL_LOCAL_GUARD"> <ShortDescription>Method tests a local variable for not null as guard and reassigns it</ShortDescription> <LongDescription>Method {1} tests a local variable for not null as guard and reassigns it</LongDescription> <Details> <![CDATA[ <p>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.</p> <p>example: <pre><code> if (name != null) { name = person.getName(); } </code></pre> It is possible this is correct, but it seems likely the guard was meant to be <code>if (name == null)</code> </p> ]]> </Details> </BugPattern> <BugPattern type="MDM_RUNTIME_EXIT_OR_HALT"> <ShortDescription>Method calls Runtime.exit() or Runtime.halt()</ShortDescription> <LongDescription>Method {1} calls {2}</LongDescription> <Details> <![CDATA[ <p>Calling <code>Runtime.exit()</code> or <code>Runtime.halt()</code> shuts down the entire Java virtual machine. This should only be done in very rare circumstances. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_RUNFINALIZATION"> <ShortDescription>Method triggers finalization</ShortDescription> <LongDescription>Method {1} triggers finalization when calling {2}</LongDescription> <Details> <![CDATA[ <p>Manually triggering finalization can result in serious performance problems and may be masking resource cleanup bugs. Only the garbage collector, not application code, should be concerned with finalization.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_BIGDECIMAL_EQUALS"> <ShortDescription>Method calls BigDecimal.equals()</ShortDescription> <LongDescription>Method {1} calls BigDecimal.equals(), which is normally a mistake</LongDescription> <Details> <![CDATA[ <p>This method calls <code>equals()</code> to compare two <code>java.math.BigDecimal</code> numbers. This is normally a mistake, as two <code>BigDecimal</code> objects are only equal if they are equal in both value and scale, so that <i>2.0</i> is not equal to <i>2.00</i>. To compare <code>BigDecimal</code> objects for mathematical equality, use <code>compareTo()</code> instead.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_INETADDRESS_GETLOCALHOST"> <ShortDescription>Method calls InetAddress.getLocalHost()</ShortDescription> <LongDescription>Method {1} calls InetAddress.getLocalHost(), which may be a security risk</LongDescription> <Details> <![CDATA[ <p>Do not call <code>InetAddress.getLocalHost()</code> on multihomed servers. On a multihomed server, <code>InetAddress.getLocalHost()</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_PROMISCUOUS_SERVERSOCKET"> <ShortDescription>Method creates promiscuous ServerSocket object</ShortDescription> <LongDescription>Method {1} creates a promiscuous ServerSocket, which may be a security risk</LongDescription> <Details> <![CDATA[ <p>Do not use the <code>ServerSocket</code> constructor or <code>ServerSocketFactory.createServerSocket()</code> factory methods that accept 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 of the <code>ServerSocket</code> constructor or <code>ServerSocketFactory.createServerSocket()</code> factory methods take a specific local address to define which network interface the socket should bind.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_RANDOM_SEED"> <ShortDescription>Method creates insecure Random object</ShortDescription> <LongDescription>Method {1} creates an insecure Random object, which may be a security risk</LongDescription> <Details> <![CDATA[ <p><code>Random()</code> constructor without a seed is insecure because it defaults to an easily guessable seed: <code>System.currentTimeMillis()</code>. Initialize a seed like <code>new Random(SecureRandom.getInstance("SHA1PRNG").nextLong())</code> or replace <code>Random()</code> with <code>SecureRandom.getInstance("SHA1PRNG")</code> instead. "SHA1PRNG" is the random algorithm supported on all platforms. </p> <p> As of Java 6, you may use <code>new Random(new SecureRandom().nextLong())</code> or <code>new SecureRandom()</code> instead. </p> ]]> </Details> </BugPattern> <BugPattern type="MDM_SECURERANDOM"> <ShortDescription>Method calls deprecated SecureRandom method</ShortDescription> <LongDescription>Method {1} calls deprecated SecureRandom method {2}</LongDescription> <Details> <![CDATA[ <p>In JDK 1.5 or less, the <code>SecureRandom()</code> constructors and <code>SecureRandom.getSeed()</code> method are recommended against using. Call <code>SecureRandom.getInstance()</code> and <code>SecureRandom.getInstance().generateSeed()</code> instead.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_THREAD_PRIORITIES"> <ShortDescription>Method uses suspicious thread priorities</ShortDescription> <LongDescription>Method {1} uses suspicious thread priorities by calling method {2}</LongDescription> <Details> <![CDATA[ <p>Getting or setting thread priorities is not portable and could cause or mask race conditions.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_THREAD_YIELD"> <ShortDescription>Method attempts to manually schedule threads</ShortDescription> <LongDescription>Method {1} attempts to manually schedule threads by calling method {2}</LongDescription> <Details> <![CDATA[ <p>Manual thread scheduling with <code>Thread.sleep()</code> or <code>Thread.yield()</code> has no guaranteed semantics and is often used to mask race conditions. These methods exist for supporting early processors when java was first released, and are not advised for modern processors. The operating system will take care of yielding threads for you.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_WAIT_WITHOUT_TIMEOUT"> <ShortDescription>Method sleeps without timeout</ShortDescription> <LongDescription>Method {1} sleeps without timeout when calling {2}</LongDescription> <Details> <![CDATA[ <p>Calling one of the following methods without timeout could block forever. Consider using a timeout to detect deadlocks or performance problems. Methods: <ul> <li>Thread.join()</li> <li>Object.wait()</li> <li>Condition.await()</li> <li>Lock.lock()</li> <li>Lock.lockInterruptibly()</li> <li>ReentrantLock.lock()</li> <li>ReentrantLock.lockInterruptibly()</li> </ul> </p> ]]> </Details> </BugPattern> <BugPattern type="MDM_THREAD_FAIRNESS"> <ShortDescription>Method ignores Lock's fairness settings by calling tryLock()</ShortDescription> <LongDescription>Method {1} ignores Lock's fairness settings by calling {2}</LongDescription> <Details> <![CDATA[ <p>Calling <code>Lock.tryLock()</code> or <code>ReentrantLock.tryLock()</code> without a timeout does not honor the lock's fairness setting. If you want to honor the fairness setting for this lock, then use <code>tryLock(0, TimeUnit.SECONDS)</code> which is almost equivalent (it also detects interruption).</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_SIGNAL_NOT_SIGNALALL"> <ShortDescription>Method calls Condition.signal() rather than Condition.signalAll()</ShortDescription> <LongDescription>Method {1} calls Condition.signal() rather than Condition.signalAll()</LongDescription> <Details> <![CDATA[ <p><code>Condition.signalAll()</code> is preferred over <code>Condition.signal()</code>. Calling <code>signal()</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_LOCK_ISLOCKED"> <ShortDescription>Method tests if a lock is locked</ShortDescription> <LongDescription>Method {1} tests if a lock is locked by calling {2}</LongDescription> <Details> <![CDATA[ <p>Calling <code>ReentrantLock.isLocked()</code> or <code>ReentrantLock.isHeldByCurrentThread()</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_STRING_BYTES_ENCODING"> <ShortDescription>Method encodes String bytes without specifying the character encoding</ShortDescription> <LongDescription>Method {1} encodes String bytes without specifying the character encoding</LongDescription> <Details> <![CDATA[ <p>The behavior of the <code>String(byte[] bytes)</code> and <code>String.getBytes()</code> is undefined if the string cannot be encoded in the platform's default charset. Instead, use the <code>String(byte[] bytes, String encoding)</code> or <code>String.getBytes(String encoding)</code> constructor which accepts the string's encoding as an argument. Be sure to specify the encoding used for the user's locale.</p> <p>As per the Java specifications, "UTF-8", "US-ASCII", "UTF-16" and "ISO-8859-1" will all be valid <a href = "http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#standard">encoding charsets</a>. If you aren't sure, try "UTF-8".</p> <p><b>New in Java 1.7</b>, you can specify an encoding from <code>StandardCharsets</code>, like <code>StandardCharsets.UTF_8</code>. These are generally preferrable because you don't have to deal with <code>UnsupportedEncodingException</code>.</p> ]]> </Details> </BugPattern> <BugPattern type="MDM_SETDEFAULTLOCALE"> <ShortDescription>Method calls Locale.setDefault()</ShortDescription> <LongDescription>Method {1} calls Locale.setDefault(), changing locale for all threads</LongDescription> <Details> <![CDATA[ <p>Do not use the <code>Locale.setDefault()</code> 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.</p> ]]> </Details> </BugPattern> <BugPattern type="ROOM_REFLECTION_ON_OBJECT_METHODS"> <ShortDescription>Method uses reflection to call a method available on java.lang.Object</ShortDescription> <LongDescription>Method {1} uses reflection to call a method available on java.lang.Object</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="IPU_IMPROPER_PROPERTIES_USE"> <ShortDescription>Method puts non-String values into a Properties object</ShortDescription> <LongDescription>Method {1} puts non-String values into a Properties object</LongDescription> <Details> <![CDATA[ <p>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.</p> <p> Don't use <code>properties.put("foo", bar);</code> </p> <p> Do use <code>properties.setProperty("foo", "bar");</code> </p> ]]> </Details> </BugPattern> <BugPattern type="IPU_IMPROPER_PROPERTIES_USE_SETPROPERTY"> <ShortDescription>Method uses Properties.put instead of Properties.setProperty</ShortDescription> <LongDescription>Method {1} uses Properties.put instead of Properties.setProperty</LongDescription> <Details> <![CDATA[ <p>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.</p> <p> Don't use <code>properties.put("foo", "bar");</code> </p> <p> Do use <code>properties.setProperty("foo", "bar");</code> </p> ]]> </Details> </BugPattern> <BugPattern type="PCAIL_POSSIBLE_CONSTANT_ALLOCATION_IN_LOOP"> <ShortDescription>Method allocates an object that is used in a constant way in a loop</ShortDescription> <LongDescription>Method {1} allocates an object that is used in a constant way in a loop</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="WOC_WRITE_ONLY_COLLECTION_LOCAL"> <ShortDescription>Method creates and initializes a collection but never reads or gains information from it</ShortDescription> <LongDescription>Method {1} creates and initializes a collection but never reads or gains information from it</LongDescription> <Details> <![CDATA[ <p>This method creates and initializes a collection but then never accesses 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.</p> ]]> </Details> </BugPattern> <BugPattern type="WOC_WRITE_ONLY_COLLECTION_FIELD"> <ShortDescription>Class creates and initializes a collection but never reads or gains information from it</ShortDescription> <LongDescription>Class {0} creates and initializes a collection but never reads or gains information from it</LongDescription> <Details> <![CDATA[ <p>This class creates and initializes a collection as a field but then never accesses 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.</p> ]]> </Details> </BugPattern> <BugPattern type="UVA_USE_VAR_ARGS"> <ShortDescription>Method defines parameter list with array as last argument, rather than vararg</ShortDescription> <LongDescription>Method {1} defines parameter list with array as last argument, rather than vararg</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="UVA_REMOVE_NULL_ARG"> <ShortDescription>Method passes explicit null value to var arg parameter</ShortDescription> <LongDescription>Method {1} passes explicit null value to var arg parameter</LongDescription> <Details> <![CDATA[ <p>This method calls a var arg method, and passes an explicit null value as the var arg parameter. It is better to just not pass any value at all, as there is confusion as to whether the null represents the entire vararg array, or the first element of the varargs array</p> ]]> </Details> </BugPattern> <BugPattern type="PUS_POSSIBLE_UNSUSPECTED_SERIALIZATION"> <ShortDescription>Method serializes an instance of a non-static inner class</ShortDescription> <LongDescription>Method {1} serializes an instance of a non-static inner class</LongDescription> <Details> <![CDATA[ <p>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 class is not desired to be serialized, either make the inner class static, or pull it out into a separate "first class" class.</p> ]]> </Details> </BugPattern> <BugPattern type="SEC_SIDE_EFFECT_CONSTRUCTOR"> <ShortDescription>Method uses a Side Effect Constructor</ShortDescription> <LongDescription>Method {1} uses a Side Effect Constructor</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="SGSU_SUSPICIOUS_GETTER_SETTER_USE"> <ShortDescription>Method uses same bean's getter value for setter</ShortDescription> <LongDescription>Method {1} uses same bean's getter value for setter</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="LGO_LINGERING_GRAPHICS_OBJECT"> <ShortDescription>Method allocations a java.awt.Graphics object without disposing it</ShortDescription> <LongDescription>Method {1} allocations a java.awt.Graphics object without disposing it</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="STB_STACKED_TRY_BLOCKS"> <ShortDescription>Method stacks similar try/catch blocks</ShortDescription> <LongDescription>Method {1} stacks similar try/catch blocks</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="CEBE_COMMONS_EQUALS_BUILDER_ISEQUALS"> <ShortDescription>Method returns the result of invoking equals() on EqualsBuilder</ShortDescription> <LongDescription>Method {1} returns the result of invoking equals() in EqualsBuilder</LongDescription> <Details> <![CDATA[ <p>This method returns the result of <code>equals</code> on the EqualsBuilder type instead of calling the method isEqual().</p> ]]> </Details> </BugPattern> <BugPattern type="CHTH_COMMONS_HASHCODE_BUILDER_TOHASHCODE"> <ShortDescription>Method returns the result of invoking hashCode() on HashCodeBuilder</ShortDescription> <LongDescription>Method {1} returns the result of invoking hashCode() in HashCodeBuilder</LongDescription> <Details> <![CDATA[ <p>This method returns the result of <code>hashCode</code> on the HashCodeBuilder type instead of calling the method toHashCode().</p> ]]> </Details> </BugPattern> <BugPattern type="CSBTS_COMMONS_STRING_BUILDER_TOSTRING"> <ShortDescription>Method returns the result of invoking toString() without intermediate invocation of append() in ToStringBuilder</ShortDescription> <LongDescription>Method {1} returns the result of invoking toString() without intermediate invocation of append() in ToStringBuilder</LongDescription> <Details> <![CDATA[ <p>This method returns the result of <code>toString</code> on a ToStringBuilder without an intermediate invocation of append().</p> ]]> </Details> </BugPattern> <BugPattern type="CCNE_COMPARE_CLASS_EQUALS_NAME"> <ShortDescription>Method compares class name instead of comparing class</ShortDescription> <LongDescription>Method {1} compares class name instead of comparing the class</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="BRPI_BACKPORT_REUSE_PUBLIC_IDENTIFIERS"> <ShortDescription>Method uses backported libraries that are now built in</ShortDescription> <LongDescription>Method {1} uses backported libraries that are now built in</LongDescription> <Details> <![CDATA[ <p>This class uses either Backport Utils concurrent classes from Emory, or Time classes from ThreeTen Backport. Updated/efficient versions of these classes are available in the version of the JDK that this code is compiled against - JDK 1.5 for the concurrent classes, and JDK 1.8 for the time classes - and these classes should only be used if you are targeting a JDK lower than this.</p> ]]> </Details> </BugPattern> <BugPattern type="CU_CLONE_USABILITY_OBJECT_RETURN"> <ShortDescription>Clone method declares it returns an Object</ShortDescription> <LongDescription>Clone method {1} declares it returns an Object</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="CU_CLONE_USABILITY_MISMATCHED_RETURN"> <ShortDescription>Clone method declares it returns a type different than the owning class</ShortDescription> <LongDescription>Clone method {1} declares it returns a type different than the owning class</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="CU_CLONE_USABILITY_THROWS"> <ShortDescription>Clone method declares it throws CloneNotSupportedException</ShortDescription> <LongDescription>Clone method {1} declares it throws CloneNotSupportedException</LongDescription> <Details> <![CDATA[ <p>This class implements the Cloneable interface but defines its clone method to still throw a CloneNotSupportedException. Since you are implementing clone() it would make sense that the method in question will <em>not</em> throw that exception, so annotating your method with it just makes clients' use of your class more painful as they have to handle an exception that will never happen. Just remove the throws clause from your method.</p> ]]> </Details> </BugPattern> <BugPattern type="CAAL_CONFUSING_ARRAY_AS_LIST"> <ShortDescription>Method calls Array.asList on an array of primitive values</ShortDescription> <LongDescription>Method {1} calls Array.asList on an array of primitive values</LongDescription> <Details> <![CDATA[ <p>This method passes an array of primitive values to the Arrays.asList call. As primitive values in arrays aren't automatically promoted to boxed primitives in arrays, the asList call cannot convert this array to 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.</p> ]]> </Details> </BugPattern> <BugPattern type="PSC_PRESIZE_COLLECTIONS"> <ShortDescription>Method does not presize the allocation of a collection</ShortDescription> <LongDescription>Method {1} does not presize the allocation of a collection</LongDescription> <Details> <![CDATA[ <p>This method allocates a collection using the default constructor even though it is known a priori (or at least can be reasonably guessed) how many items are going to be placed in the collection, and thus needlessly causes intermediate reallocations of the collection.</p> <p>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.</p> <p>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: <ul> <li>Sets.newHashSetWithExpectedSize(int)</li> <li>Maps.newHashMapWithExpectedSize(int)</li> </ul> If not, a good estimate would be the expectedSize / {LOADING_FACTOR} which by default is 0.75 </p> ]]> </Details> </BugPattern> <BugPattern type="PSC_SUBOPTIMAL_COLLECTION_SIZING"> <ShortDescription>Method uses suboptimal sizing to allocate a collection</ShortDescription> <LongDescription>Method {1} uses suboptimal sizing to allocate a collection</LongDescription> <Details> <![CDATA[ <p>This method allocates a collection using the a constructor that takes a size parameter. However, because Maps and Sets have a loading factor, passing in the exact size you want is an incorrect way to presize the collection, and may still cause reallocations. Since you are using Guava, it is better to use <code><pre> Maps.newHashMapWithExpectedSize(c.size()); </pre></code> or <code><pre> Sets.newHashSetWithExpectedsize(c.size()); </pre></code> as this method calculates the correct size taking into account the loading factor. Alternatively, if you know that the collection will not grow beyond the initial size, you can specify a load factor of 1.0F in the constructor. </p> ]]> </Details> </BugPattern> <BugPattern type="UMTP_UNBOUND_METHOD_TEMPLATE_PARAMETER"> <ShortDescription>Method declares unbound method template parameter(s)</ShortDescription> <LongDescription>Method {1} declares unbound method template parameter(s)</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="NPMC_NON_PRODUCTIVE_METHOD_CALL"> <ShortDescription>Method ignores return value of a non mutating method</ShortDescription> <LongDescription>Method {1} ignores return value of a non mutating method</LongDescription> <Details> <![CDATA[ <p>This method ignores the return value of a common method that is assumed to be non-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.</p> ]]> </Details> </BugPattern> <BugPattern type="AIOB_ARRAY_INDEX_OUT_OF_BOUNDS"> <ShortDescription>Method attempts to access an array element outside the array's size</ShortDescription> <LongDescription>Method {1} attempts to access an array element outside the array's size</LongDescription> <Details> <![CDATA[ <p>This method accesses an array element using a literal index that is known to be outside the size of the specified array. This will cause an ArrayIndexOutOfBoundsException at runtime.</p> ]]> </Details> </BugPattern> <BugPattern type="AIOB_ARRAY_STORE_TO_NULL_REFERENCE"> <ShortDescription>Method attempts to store an array element to an array that does not appear to be allocated</ShortDescription> <LongDescription>Method {1} attempts to store an array element to an array that does not appear to be allocated</LongDescription> <Details> <![CDATA[ <p>This method attempts to store an array element into an array that appears not to have been allocated.</p> ]]> </Details> </BugPattern> <BugPattern type="ICA_INVALID_CONSTANT_ARGUMENT"> <ShortDescription>Method passes an invalid value as a method argument</ShortDescription> <LongDescription>Method {1} passes an invalid value as a method argument</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="CNC_COLLECTION_NAMING_CONFUSION"> <ShortDescription>Collection variable is named with a different type of collection in the name</ShortDescription> <LongDescription>Collection variable {1} is named with a different type of collection in the name</LongDescription> <Details> <![CDATA[ <p>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<User> called userList. This is confusing to the reader, and likely caused by a previous refactor of type, without changing the name. This detector is obviously only checking for English names.</p> ]]> </Details> </BugPattern> <BugPattern type="PME_POOR_MANS_ENUM"> <ShortDescription>Simple field is used like an enum</ShortDescription> <LongDescription>Simple field {1} is used like an enum</LongDescription> <Details> <![CDATA[ <p>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. </p> ]]> </Details> </BugPattern> <BugPattern type="UP_UNUSED_PARAMETER"> <ShortDescription>Static or private method has unused parameters</ShortDescription> <LongDescription>Static or private method {1} has unused parameters</LongDescription> <Details> <![CDATA[ <p>This method defines parameters that are never used. As this method is either static or 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. In this case, it is likely that once you remove the parameter, there will be a chain of method calls that have spent time creating this parameter and passing it down the line. All of this may be able to be removed.</p> ]]> </Details> </BugPattern> <BugPattern type="FCCD_FIND_CLASS_CIRCULAR_DEPENDENCY"> <ShortDescription>Class has a circular dependency with other classes</ShortDescription> <LongDescription>Class {0} has a circular dependency with other classes</LongDescription> <Details> <![CDATA[ <p> 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. The dependency chain can be seen in the GUI version of FindBugs. </p> ]]> </Details> </BugPattern> <BugPattern type="MUC_MODIFYING_UNMODIFIABLE_COLLECTION"> <ShortDescription>This method attempts to modify collection that appears to possibly be immutable</ShortDescription> <LongDescription>This method {1} attempts to modify collection that appears to possibly be immutable</LongDescription> <Details> <![CDATA[ <p>This method attempts to modify a collection that it got from a source that could potentially have created an immutable collection, through Arrays.asList, Collections.unmodifiableXXX, or one of Guava's methods. Doing so will cause an exception, as these collections are not mutable.</p> ]]> </Details> </BugPattern> <BugPattern type="HES_EXECUTOR_NEVER_SHUTDOWN"> <ShortDescription>ExecutorService field doesn't ever get shutdown</ShortDescription> <LongDescription>ExecutorService {2} is instantiated, but never shutdown, potentially preventing the entire JVM from shutting down</LongDescription> <Details> <![CDATA[ <p>Most <code>ExecutorService</code> objects must be explicitly shut down, otherwise their internal threads can prolong the running of the JVM, even when everything else has stopped.</p> <p>FindBugs has detected that there are no calls to either the <code>shutdown()</code> or <code>shutdownNow()</code> method, and thus, the <code>ExecutorService</code> is not guaranteed to ever terminate. This is especially problematic for <code>Executors.newFixedThreadPool()</code> and most of the other convenience methods in the <code>Executors</code> class.</p> <p>Even though there are some exceptions to this, particularly when a custom <code>ThreadFactory</code> is provided, or for <code>ThreadPoolExecutor</code>s with <code>allowsCoreThreadTimeOut()</code> set to true, it is good practice to explicitly shutdown the <code>ExecutorService</code> when its utility is done.</p> ]]> </Details> </BugPattern> <BugPattern type="HES_LOCAL_EXECUTOR_SERVICE"> <ShortDescription>Suspicious Local Executor Service</ShortDescription> <LongDescription>ExecutorService is created as a local variable, which is unusual</LongDescription> <Details> <![CDATA[ <p><code>ExecutorService</code>s are typically instantiated as fields so that many tasks can be executed on a controlled number of <code>Thread</code>s across many method calls. Therefore, it is unusual for <code>ExecutorService</code>s to be a local variable, where tasks will be added only one time, in the enclosing method. </p> <p>Furthermore, when a local <code>ExecutorService</code> reaches the end of scope and goes up for garbage collection, the internal <code>Thread</code>s are not necessarily terminated and can prevent the JVM from ever shutting down.</p> <p>Consider making this local variable a field and creating a method that will explicitly shut down the <code>ExecutorService</code></p> ]]> </Details> </BugPattern> <BugPattern type="HES_EXECUTOR_OVERWRITTEN_WITHOUT_SHUTDOWN"> <ShortDescription>An ExecutorService isn't shutdown before the reference to it is lost</ShortDescription> <LongDescription>ExecutorService {2} is replaced with another ExecutorService without being shutdown, potentially preventing the entire JVM from shutting down</LongDescription> <Details> <![CDATA[ <p>Most <code>ExecutorService</code> objects must be explicitly shut down, otherwise their internal threads can prevent the JVM from ever shutting down, even when everything else has stopped.</p> <p>FindBugs has detected that something like the following is happening:<br/> <pre><code> ExecutorService executor = ... //e.g. Executors.newCachedThreadPool(); ... public void reset() { this.executor = Executors.newCachedThreadPool(); this.executor.execute(new SampleExecutable()); }<br/> </code></pre> For normal objects, losing the last reference to them like this would trigger the object to be cleaned up in garbage collection. For <code>ExecutorService</code>s, this isn't enough to terminate the internal threads in the thread pool, and the <code>ExecutorService</code> isn't guaranteed to shut down, causing the JVM to never stop. <br/> To fix this, simply add a call to <code>shutdown()</code> like this:<br/> <pre><code> ExecutorService executor = ... //e.g. Executors.newCachedThreadPool(); ... public void reset() { this.executor.shutDown(); //Fix this.executor = Executors.newCachedThreadPool(); this.executor.execute(new SampleExecutable()); } </code></pre> </p> <p>Even though there are some exceptions to this, particularly when a custom <code>ThreadFactory</code> is provided, or for <code>ThreadPoolExecutor</code>s with <code>allowsCoreThreadTimeOut()</code> set to true, it is good practice to explicitly shut down the <code>ExecutorService</code> at the end of execution, or when it is being replaced.</p> <p><b>Note:</b> <code>ExecutorService</code>s are generally created once in a program's life cycle. If you find yourself replacing the <code>ExecutorService</code>, perhaps you may consider restructuring your code to use calls like <code>awaitTermination()</code> or <code>Future</code>s/<code>Callable</code>s to avoid recreating the <code>ExecutorService</code>.</p> ]]> </Details> </BugPattern> <BugPattern type="HCP_HTTP_REQUEST_RESOURCES_NOT_FREED_FIELD"> <ShortDescription>Unreleased HttpRequest network resources (field)</ShortDescription> <LongDescription>The HttpRequest field {1} does not release its network resources, which could freeze the running code</LongDescription> <Details> <![CDATA[ <p>FindBugs has detected an <code>org.apache.http.HttpRequest</code> (e.g. <code>HttpGet</code>, <code>HttpPost</code>, etc) that didn't release its associated resources. Code like the following: <br/> <pre>code> 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; } </code></pre> will freeze after a few requests, usually with no indication as to why. </p> <p> The reason this code freezes is because <code>org.apache.http.HttpRequest</code>s need to explicitly release their connection with a call to either <code>reset()</code> or <code>releaseConnection()</code>. The above example can be easily fixed:<br/> <pre><code> 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(); } <b>finally { this.httpGet.reset(); }</b> return null; }<br/> </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="HCP_HTTP_REQUEST_RESOURCES_NOT_FREED_LOCAL"> <ShortDescription>Unreleased HttpRequest network resources (local)</ShortDescription> <LongDescription>The local HttpRequest {1} does not release its network resources before being garbage collected, which could freeze the running code</LongDescription> <Details> <![CDATA[ <p>FindBugs has detected an <code>org.apache.http.HttpRequest</code> (e.g. <code>HttpGet</code>, <code>HttpPost</code>, etc) that didn't release its associated resources. Code like the following: <br/> <pre><code> 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; } </code></pre> will freeze after a few requests, usually with no indication as to why. </p> <p> The reason this code freezes is because <code>org.apache.http.HttpRequest</code>s need to explicitly release their connection with a call to either <code>reset()</code> or <code>releaseConnection()</code>, <b>even if the request is a local</b>. The garbage collector will not release these resources, leading to the frustrating freezing scenario described above. <br/>The above example can be easily fixed:<br/> <pre><code> public String requestInfo(URI u) { HttpGet httpGet = new HttpGet(u); try(CloseableHttpResponse response = client.execute(httpGet);) { return getResponseAsString(response); } catch (IOException e) { e.printStackTrace(); } <b>finally { httpGet.reset(); }</b> return null; } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="UJM_UNJITABLE_METHOD"> <ShortDescription>This method is too long to be compiled by the JIT</ShortDescription> <LongDescription>This method {1} is too long to be compiled by the JIT</LongDescription> <Details> <![CDATA[ <p>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 into smaller chunks. (And it's probably a good idea for readability too!)</p> ]]> </Details> </BugPattern> <BugPattern type="CTU_CONFLICTING_TIME_UNITS"> <ShortDescription>This method performs arithmetic operations on time values with different units</ShortDescription> <LongDescription>This method {1} performs arithmetic operations on time values with different units</LongDescription> <Details> <![CDATA[ <p>This method takes two values that appear to be representing time, and performs arithmetic operations on these 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.</p> ]]> </Details> </BugPattern> <BugPattern type="CSI_CHAR_SET_ISSUES_USE_STANDARD_CHARSET"> <ShortDescription>This method needlessly uses a String literal as a Charset encoding</ShortDescription> <LongDescription>This method "{3}" needlessly uses a String literal to define an encoding. A built-in Charset could be used instead like: {4}</LongDescription> <Details> <![CDATA[ <p>This method uses a string literal to specify a <code>Charset</code> encoding. However, the method invoked has an alternative signature that takes a <code>Charset</code> object. You should use this signature, as this class is compiled with JDK 7 (or better), and the <code>Charset</code> in question is available as a constant from the <code>java.nio.charset.StandardCharsets</code> class.</p> <p>Instead of specifying "UTF-8", use <code>StandardCharsets.UTF_8</code>, for instance. An added benefit of this is that you will not need to catch <code>UnsupportedEncodingException</code>.</p> ]]> </Details> </BugPattern> <BugPattern type="CSI_CHAR_SET_ISSUES_USE_STANDARD_CHARSET_NAME"> <ShortDescription>This method should use a StandardCharsets.XXX.name() to specify an encoding</ShortDescription> <LongDescription>This method {3} should use a StandardCharsets.XXX.name() to specify an encoding</LongDescription> <Details> <![CDATA[ <p>This method uses a hand-typed <code>String</code> literal to specify a <code>Charset</code> encoding. As this class is compiled with JDK 7 (or better), and the charset in question is available as a constant from the <code>java.nio.charset.StandardCharsets</code> class, it is better to use the .name() method of the appropriate <code>StandardCharsets</code> constant.</p> <p>The method in question doesn't directly support a <code>Charset</code> as a parameter, only a <code>String</code>. Still, instead of specifying something like "UTF-8" (and potentially mistyping it), use <code>StandardCharsets.UTF_8.name()</code>. </p> ]]> </Details> </BugPattern> <BugPattern type="CSI_CHAR_SET_ISSUES_UNKNOWN_ENCODING"> <ShortDescription>This method uses an unknown character encoding literal</ShortDescription> <LongDescription>This method {3} uses an unknown character encoding literal "{4}"</LongDescription> <Details> <![CDATA[ <p>This method specifies a <code>Charset</code> 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 seems dubious that this is the case.</p> <p> The standard JDK encodings (for Java 8) are "UTF-8", "US-ASCII", "ISO-8859-1", "UTF-16BE", "UTF-16LE", "UTF-16". These are all case-sensitive. </p> ]]> </Details> </BugPattern> <BugPattern type="CBC_CONTAINS_BASED_CONDITIONAL"> <ShortDescription>This method uses an excessively complex conditional that can be replaced with Set.contains</ShortDescription> <LongDescription>This method {1} uses an excessively complex conditional that can be replaced with Set.contains</LongDescription> <Details> <![CDATA[ <p>This method uses an overly complex <code>if</code> 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 grows, 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.</p> ]]> </Details> </BugPattern> <BugPattern type="OPM_OVERLY_PERMISSIVE_METHOD"> <ShortDescription>This method is declared more permissively than is used in the code base</ShortDescription> <LongDescription>This method {1} is declared more permissively than is used in the code base</LongDescription> <Details> <![CDATA[ <p>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: <ul> <li>The method is called from code not being scanned, such as unit tests</li> <li>The method is an API method, expected to be used by unknown client code</li> <li>The method is called through reflection </ul> </p> ]]> </Details> </BugPattern> <BugPattern type="STT_TOSTRING_STORED_IN_FIELD"> <ShortDescription>This method stores the value of a toString() call into a field</ShortDescription> <LongDescription>This method {0} stores the value of a toString() call into a field</LongDescription> <Details> <![CDATA[ <p>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. </p> ]]> </Details> </BugPattern> <BugPattern type="STT_STRING_PARSING_A_FIELD"> <ShortDescription>This method parses a String that is a field</ShortDescription> <LongDescription>This method {1} parses a String that is a field</LongDescription> <Details> <![CDATA[ <p>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. </p> ]]> </Details> </BugPattern> <BugPattern type="STT_TOSTRING_MAP_KEYING"> <ShortDescription>This method uses a concatenated String as a map key</ShortDescription> <LongDescription>This method {1} uses a concatenated String as a map key</LongDescription> <Details> <![CDATA[ <p>This method builds a key for a map, using a StringBuilder, either implicitly or explicitly. This means the type of the key is something more than a String constant, it is a properly formatted String. However, there is no type based verification that all uses of this key will follow this formatting. It is much better to use a proper, simple, bean class that holds two (or more) fields so that it is clear what is expected for key use. </p> <p> Example<br/> instead of <pre><code> V v = myMap.get(tableName + "-" + columnName); </code></pre> use <pre><code> V v = myMap.get(new ColumnSpec(tableName, columnName)); </code></pre> where ColumnSpec is a simple bean-like class of your creation. The advantages, are <ul> <li>The ColumnSpec fully describes what is expected, you need a tableName and columnName</li> <li>There is no guessing by the programmer what the format is, was it tableName + "_" + columnName?</li> </ul> </p> ]]> </Details> </BugPattern> <BugPattern type="SLS_SUSPICIOUS_LOOP_SEARCH"> <ShortDescription>This method continues a loop after finding an equality condition</ShortDescription> <LongDescription>This method {1} continues a loop after finding an equality condition</LongDescription> <Details> <![CDATA[ <p>This method continues with a loop, and does not break out of it, after finding and setting a variable in an <code>if</code> 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.</p> <p>Example: <pre><code> int age = 0; for (Person p : people) { if (p.getName().equals("Dave")) { age = p.getAge(); } } </code></pre> It is likely you wanted a break after getting the age for "Dave".</p> ]]> </Details> </BugPattern> <BugPattern type="CRF_CONFLATING_RESOURCES_AND_FILES"> <ShortDescription>This method accesses URL resources using the File API</ShortDescription> <LongDescription>This method {1} accesses URL resources using the File API</LongDescription> <Details> <![CDATA[ <p>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. To avoid this confusing inconsistency, use the URL.openStream API instead to access the data of the classpath resource. </p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_NO_EQUALS"> <ShortDescription>Class does not implement an equals method</ShortDescription> <LongDescription>Class {0} does not implement an equals method</LongDescription> <Details> <![CDATA[ <p>This class, which has instance fields, has no equals(Object o) method. It is possible that this class is never used in a context where this is required; it is often assumed, however, from clients of this class that it is, so it is good to add such methods when you create them. </p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_NO_HASHCODE"> <ShortDescription>Class does not implement a hashCode method</ShortDescription> <LongDescription>Class {0} does not implement a hashCode method</LongDescription> <Details> <![CDATA[ <p>This class, which has instance fields, has no hashCode() method. It is possible that this class is never used in a context where this is required; it is often assumed, however, from clients of this class that it is, so it is good to add such methods when you create them. </p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_NO_PACKAGE"> <ShortDescription>Class is defined in the default package</ShortDescription> <LongDescription>Class {0} id defined in the default package</LongDescription> <Details> <![CDATA[ <p>This class has been created in the default package. Classes should be defined in a proper package structure, typically defined by the reverse of the domain name of the owner of the code base. Putting code in the default (no) package limits its usefulness, including: <ol> <li>Not being able to import this class into classes with packages</li> <li>Leaving it open to name collisions with other packages.</li> </ol> </p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_NO_TOSTRING"> <ShortDescription>Class does not implement a toString method</ShortDescription> <LongDescription>Class {0} does not implement a toString method</LongDescription> <Details> <![CDATA[ <p>This class, which has instance fields, has no toString() method, which will make debugging with this class more difficult than it could be. Consider adding a toString() method. Using libraries like commons-lang3 ToStringBuilder makes this process easy. </p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_IDE_GENERATED_PARAMETER_NAMES"> <ShortDescription>Method uses IDE generated parameter names</ShortDescription> <LongDescription>Method {1} uses IDE generated parameter names</LongDescription> <Details> <![CDATA[ <p>This method appears to have been generated from an interface or superclass using an IDE. As such the IDE generated generic names (arg0, arg1, arg2) for parameters for this method, and the author of this method did not change them to be meaningful. For better understandability it is recommended that you name these parameters with regard to their function.</p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_PRINTSTACKTRACE"> <ShortDescription>Method prints the stack trace to the console</ShortDescription> <LongDescription>Method {1} prints the stack trace to the console</LongDescription> <Details> <![CDATA[ <p>This method prints a stack trace to the console. This is non configurable, and causes an application to look unprofessional. Switch to using loggers so that users can control what is logged and where.</p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_WRONG_FIELD_ORDER"> <ShortDescription>Class orders instance fields before static fields</ShortDescription> <LongDescription>Class {0} orders instance fields before static fields</LongDescription> <Details> <![CDATA[ <p>This class defines fields in an order that is confusing, and not expected by other developers. The standard is for static fields to be listed first, followed by instance fields. When fields are listed out of order, developers may make assumptions about their behaviour that are incorrect and lead to bugs.</p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_UPPER_PACKAGE"> <ShortDescription>Class is defined in a package with upper case characters</ShortDescription> <LongDescription>Class {0} is defined in a package with upper case characters</LongDescription> <Details> <![CDATA[ <p>This class is defined within a package that uses upper case letters. Package names are expected to be in the form of all lowercase.</p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_LOWER_CLASS"> <ShortDescription>Class does not start with an upper case letter</ShortDescription> <LongDescription>Class {0} does not start with an upper case letter</LongDescription> <Details> <![CDATA[ <p>This class has been given a name that does not start with an upper case letter. Classes should follow a pattern of uppercasing the first letter of each word, AsAnExample</p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_BAD_SERIALVERSIONUID"> <ShortDescription>Class defines a computed serialVersionUID that doesn't equate to the calculated value</ShortDescription> <LongDescription>Class {0} defines a computed serialVersionUID that doesn't equate to the calculated value</LongDescription> <Details> <![CDATA[ <p>This serializable class defines a serialVersionUID that appears to be a computed value, however the value does not match the computed value, and thus losses it's value as version indicator. Either create a custom value like 1, 2, 3, 4.. etc, or recompute the serialVersionUID using your IDE.</p> ]]> </Details> </BugPattern> <BugPattern type="IMC_IMMATURE_CLASS_VAR_NAME"> <ShortDescription>Class defines a field or local variable named 'var'</ShortDescription> <LongDescription>Class {0} defines a field or local variable named 'var'</LongDescription> <Details> <![CDATA[ <p>A field or variable is named 'var' which will conflict with the built in Java 10 feature using 'var' as a keyword.</p> ]]> </Details> </BugPattern> <BugPattern type="JXI_GET_ENDPOINT_CONSUMES_CONTENT"> <ShortDescription>JAX-RS Method implements a GET request but consumes input</ShortDescription> <LongDescription>JAX-RS Method {1} implements a GET request but consumes input</LongDescription> <Details> <![CDATA[ <p>This JAX-RS endpoint is annotated to be used with @GET requests, but also documents that it consumes JSON or XML data. Since a GET request pulls parameters from the URL, and not the body of the request, this pattern is problematic. If you wish to consume JSON or XML data, this request should be annotated with @POST.</p> ]]> </Details> </BugPattern> <BugPattern type="JXI_INVALID_CONTEXT_PARAMETER_TYPE"> <ShortDescription>JAX-RS Method specifies an invalid @Context parameter type</ShortDescription> <LongDescription>JAX-RS {1} Method specifies an invalid @Context parameter type</LongDescription> <Details> <![CDATA[ <p>This JAX-RS endpoint annotates a parameter with a @Context annotation. This annotation can supply values for the following types: <ul> <li>javax.ws.rs.core.UriInfo</li> <li>javax.ws.rs.core.HttpHeaders</li> <li>javax.ws.rs.core.Request</li> <li>javax.ws.rs.core.SecurityContext</li> <li>javax.ws.rs.ext.Providers</li> <li>javax.servlet.ServletConfig</li> <li>javax.servlet.ServletContext</li> <li>javax.servlet.HttpServletRequest</li> <li>javax.servlet.HttpServletResponse</li> </ul> It is possible that your container can supply additional types, but these types are not standard and may not be supported on other application servers.</p> ]]> </Details> </BugPattern> <BugPattern type="JXI_PARM_PARAM_NOT_FOUND_IN_PATH"> <ShortDescription>JAX-RS Method specifies non-resolveable @PathParam</ShortDescription> <LongDescription>JAX-RS Method {1} specifies non-resolveable @PathParam</LongDescription> <Details> <![CDATA[ <p>This JAX-RS endpoint has a @PathParam specified that is not found in the @Path annotation and thus can not determine from where to populate that parameter.</p> ]]> </Details> </BugPattern> <BugPattern type="JXI_UNDEFINED_PARAMETER_SOURCE_IN_ENDPOINT"> <ShortDescription>JAX-RS Method defines a parameter that has no @*Param or @Context annotation, or @Consumes method annotation</ShortDescription> <LongDescription>JAX-RS Method {1} defines a parameter that has no @*Param or @Context annotation, or @Consumes method annotation</LongDescription> <Details> <![CDATA[ <p>This JAX-RS endpoint declares a parameter without specifying where the value of this parameter comes from. You can specify this by using one of several 'Param' annotations (@PathParam, @CookieParam, @FormParam @HeaderParam @MatrixParam @QueryParam), by adding a @Context parameter annotation, or you can declare that the method @Consumes an XML or JSON stream.</p> ]]> </Details> </BugPattern> <BugPattern type="JPAI_TRANSACTION_ON_NON_PUBLIC_METHOD"> <ShortDescription>Method has a Spring @Transactional annotation on it, but is non-public</ShortDescription> <LongDescription>Method {1} has a Spring @Transactional annotation on it, but is non-public</LongDescription> <Details> <![CDATA[ <p>This method specifies a Spring @Transactional annotation but the method is defined as being non-public. Spring only creates transactional boundaries on methods that are public, and so this annotation is not doing anything for this method. Make the method public, or place the annotation on a more appropriate method.</p> ]]> </Details> </BugPattern> <BugPattern type="JPAI_HC_EQUALS_ON_MANAGED_ENTITY"> <ShortDescription>JPA Entity with Generated @Id defined with hashCode/equals</ShortDescription> <LongDescription>JPA Entity {0} with Generated @Id defined with hashCode/equals</LongDescription> <Details> <![CDATA[ <p>This class is defined to be a JPA Entity, and has an @Id field that is generated by the JPA provider. Since you do not control when that Id is created directly, it is risky to implement hashCode/equals for this class, and especially for use with Collections, as the data behind the algorithms will not be immutable, and thus cause problems when those fields change, and the object is in the collection. It is usually safer to not define hashCode and equals for entity objects, but treat them as objects for IdentityHashSet/Maps instead.</p> ]]> </Details> </BugPattern> <BugPattern type="JPAI_NON_PROXIED_TRANSACTION_CALL"> <ShortDescription>Method annotated with @Transactional is called from a non Spring proxy</ShortDescription> <LongDescription>Method {1} annotated with @Transactional is called from a non Spring proxy</LongDescription> <Details> <![CDATA[ <p>This method call is to a method that has a @Transactional annotation on it. However, since this call is from the same class, it is not going through any Spring proxy, and thus the transactional quality of this method is completely lost. @Transactional methods must always be called through a Spring bean that is autowired.</p> ]]> </Details> </BugPattern> <BugPattern type="JPAI_INEFFICIENT_EAGER_FETCH"> <ShortDescription>OneToMany join specifies 1+n EAGER join</ShortDescription> <LongDescription>OneToMany join specifies 1+n EAGER join</LongDescription> <Details> <![CDATA[ <p>This JPA entity specifies a @OneToMany join with a fetch type of EAGER. By default EAGER joins perform select operations on each element returned from the original query in sequence, thus producing 1 + n queries. If you are going to use EAGER joins, it is wise to specify a Join type by using @Fetch annotations in Hibernate or @JoinFetch/@BatchFetch annotations (or hints) in EclipseLink, for example. Even so, these annotations may only apply in limited cases, such as in the use of find.</p> ]]> </Details> </BugPattern> <BugPattern type="JPAI_IGNORED_MERGE_RESULT"> <ShortDescription>Method ignores the return value of EntityManager.merge</ShortDescription> <LongDescription>Method {1} ignores the return value of EntityManager.merge</LongDescription> <Details> <![CDATA[ <p>This method calls EntityManager.merge, and throws away the resultant value. This result is the managed entity version of the potentially unmanaged object that was passed to merge. You should use the returned managed entity for any further use.</p> ]]> </Details> </BugPattern> <BugPattern type="JPAI_NON_SPECIFIED_TRANSACTION_EXCEPTION_HANDLING"> <ShortDescription>Method does not specify how to handle transaction when exception is thrown</ShortDescription> <LongDescription>Method {1} does not specify how to handle transaction when exception is thrown</LongDescription> <Details> <![CDATA[ <p>This method declares that it throws one or more non-runtime exceptions. It also is annotated with a @Transactional annotation but fails to describe whether to rollback the transaction or not based on this thrown exception. Use 'rollbackFor' or 'noRollbackFor' attributes of the Transactional annotation to document this.</p> ]]> </Details> </BugPattern> <BugPattern type="JPAI_UNNECESSARY_TRANSACTION_EXCEPTION_HANDLING"> <ShortDescription>Method declares handling a transactional exception that won't be thrown</ShortDescription> <LongDescription>Method {1} declares handling a transactional exception that won't be thrown</LongDescription> <Details> <![CDATA[ <p>This method declares that it either rolls back or does not rollback a transaction based on an expected exception being thrown. However, neither this exception, nor any derived exceptions can be thrown from this method, and so the annotation is useless.</p> ]]> </Details> </BugPattern> <BugPattern type="SEO_SUBOPTIMAL_EXPRESSION_ORDER"> <ShortDescription>Method orders expressions in a conditional in a sub optimal way</ShortDescription> <LongDescription>Method {1} orders expressions in a conditional in a sub optimal way</LongDescription> <Details> <![CDATA[ <p>This method builds a conditional expression, for example, in an <code>if</code> or <code>while</code> statement, where the expressions contain both simple local variable comparisons and comparisons on method calls. The expression orders these so that the method calls come before the simple local variable comparisons. This causes method calls to be executed in conditions when they do not need to be, and thus potentially causes a lot of code to be executed for nothing. By ordering the expressions so that the simple conditions containing local variable conditions are first, you eliminate this waste. This assumes that the method calls do not have side effects. If the methods do have side effects, it is probably a better idea to pull these calls out of the condition and execute them first, assigning a value to a local variable. In this way you give a hint that the call may have side effects.</p> <p>Example: <pre><code> if ((calculateHaltingProbability() > 0) && shouldCalcHalting) { } </code></pre> would be better as <pre><code> if (shouldCalcHalting && (calculateHaltingProbability() > 0) { } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="IOI_DOUBLE_BUFFER_COPY"> <ShortDescription>Method passes a Buffered Stream/Reader/Writer to a already buffering copy method</ShortDescription> <LongDescription>Method {1} passes a Buffered Stream/Reader/Writer to a already buffering copy method</LongDescription> <Details> <![CDATA[ <p>This method copies data from input to output using streams or reader/writers using a well known copy method, from java.nio, commons-io, springframework, guava or poi. These methods are efficient in that they copy these files using buffers. However, this method is also buffering the streams, causing a double buffering to occur. So data first goes to one buffer, then is copied to another buffer, before making it to the destination (or vice-versa). This just causes the copy operation to be inefficient both from a time perspective and a memory allocation one. When using these copy methods, do not pass buffered streams/readers/writers.</p> ]]> </Details> </BugPattern> <BugPattern type="IOI_COPY_WITH_READER"> <ShortDescription>Method performs bulk stream copy with a java.io.Reader derived input</ShortDescription> <LongDescription>Method {1} performs bulk stream copy with a java.io.Reader derived input</LongDescription> <Details> <![CDATA[ <p>This method copies data from a java.io.Reader derived class to an output class, using a bulk copy method supplied by java.nio, commons-io, springframework, guava or poi. Since you are copying the entire stream, you don't care about its contents, and thus using a Reader is wasteful, as a reader has to do the hard work of converting byte data to characters, when there is no need to do this. Use stream based inputs for better performance.</p> ]]> </Details> </BugPattern> <BugPattern type="IOI_USE_OF_FILE_STREAM_CONSTRUCTORS"> <ShortDescription>Method uses a FileInputStream or FileOutputStream constructor</ShortDescription> <LongDescription>Method {1} uses a FileInputStream or FileOutputStream constructor</LongDescription> <Details> <![CDATA[ <p>This method creates and uses a java.io.FileInputStream or java.io.FileOutputStream object. Unfortunately both of these classes implement a finalize method, which means that objects created will likely hang around until a full garbage collection occurs, which will leave excessive garbage on the heap for longer, and potentially much longer than expected. Java 7 introduced two ways to create streams for reading and writing files that do not have this concern. You should consider switching from these above classes to <code> InputStream is = java.nio.file.Files.newInputStream(myfile.toPath()); OutputStream os = java.nio.file.Files.newOutputStream(myfile.toPath()); </code> </p> ]]> </Details> </BugPattern> <BugPattern type="IOI_UNENDED_ZLIB_OBJECT"> <ShortDescription>Method creates a ZLIB Inflater or Deflater and doesn't appear to end() it</ShortDescription> <LongDescription>Method {1} creates a ZLIB Inflater or Deflater and doesn't appear to end() it</LongDescription> <Details> <![CDATA[ <p>This method constructs a java.util.zip.Inflater or java.util.zip.Deflater and does not appear to call end() on it. This will cause a potentially large amount of memory to hang around inside the object until the object gets garbage collected. To avoid this unnecessary bloat, put a call to end() in a finally block of the code where you are using this instance. </p> ]]> </Details> </BugPattern> <BugPattern type="DMC_DUBIOUS_MAP_COLLECTION"> <ShortDescription>Class holds a map-type field, but uses it as only a List</ShortDescription> <LongDescription>Class {0} holds a map-type field {1}, but uses it as only a List</LongDescription> <Details> <![CDATA[ <p>This method instantiates a map-type field in a static initializer or constructor, but then only uses it through iteration. This means that this data structure should really just be a List<SomeObject>, where the class held by the list contains the two fields held by the key and value of the Map. It was likely done this way to avoid having to create a class, but this just obfuscates the purpose of the field. </p> ]]> </Details> </BugPattern> <BugPattern type="BL_BURYING_LOGIC"> <ShortDescription>Method buries logic to the right (indented) more than it needs to be</ShortDescription> <LongDescription>Method {1} buries logic to the right (indented) more than it needs to be</LongDescription> <Details> <![CDATA[ <p>Looks for relatively large <code>if</code> blocks of code, where you unconditionally return from them, and then follow that with an unconditional return of a small block. This places the bulk of the logic to the right indentation-wise, making it more difficult to read than needed. It would be better to invert the logic of the if block, and immediately return, allowing the bulk of the logic to be move to the left for easier reading.</p> ]]> </Details> </BugPattern> <BugPattern type="WI_DUPLICATE_WIRED_TYPES"> <ShortDescription>Class auto wires the same object into two separate fields in a class hierarchy</ShortDescription> <LongDescription>Class {0} auto wires the same object into two separate fields in a class hierarchy</LongDescription> <Details> <![CDATA[ <p>This class has two fields in either itself or a parent class, which autowire (without specialization) the same object for both fields. This is likely caused by a developer just not being aware that the field already is available for your use, and just causes wasted space, and confuses code access to the same object through two different pathways.</p> ]]> </Details> </BugPattern> <BugPattern type="WI_MANUALLY_ALLOCATING_AN_AUTOWIRED_BEAN"> <ShortDescription>Method allocates an object with new when the class is defined as an autowireable bean</ShortDescription> <LongDescription>Method {1} allocates an object with new when the class is defined as an autowireable bean</LongDescription> <Details> <![CDATA[ <p>This method allocates an object with new, but the class of the object that is being created is marked with a Spring annotation denoting that this class is to be used through an @Autowire annotation. Allocating it with <code>new</code> will likely mean that fields on the class will not be autowired, but instead be null. You should just autowire an instance of this class into the class in question, or if need be, use Spring's getBean(name) method to fetch one.</p> ]]> </Details> </BugPattern> <BugPattern type="WI_WIRING_OF_STATIC_FIELD"> <ShortDescription>Static field is autowired</ShortDescription> <LongDescription>Static Field {1} is autowired</LongDescription> <Details> <![CDATA[ <p>Autowiring of static fields does not work using simple @Autowire annotations, not should you attempt to do so as it's an anti pattern. Use PostConstruct methods to initialize static fields if you must do something like this.</p> ]]> </Details> </BugPattern> <BugPattern type="CCI_CONCURRENT_COLLECTION_ISSUES_USE_PUT_IS_RACY"> <ShortDescription>Method gets and sets a value of a ConcurrentHashMap in a racy manner</ShortDescription> <LongDescription>Method {1} gets and sets a value of a ConcurrentHashMap in a racy manner </LongDescription> <Details> <![CDATA[ <p>This method retrieves the value of a key from a ConcurrentHashMap, where the value is itself a collection. It checks this value for null, and if it is so, creates a new collection and places it in the map. This may cause thread race conditions where two threads overwrite each other's values. You should be using <code> ConcurrentHashMap.putIfAbsent(K, V) </code> instead. ]]> </Details> </BugPattern> <BugPattern type="UTWR_USE_TRY_WITH_RESOURCES"> <ShortDescription>Method manually handles closing an auto-closeable resource</ShortDescription> <LongDescription>Method {1} manually handles closing an auto-closeable resource</LongDescription> <Details> <![CDATA[[ <p>This method allocates and uses an auto closeable resource. However, it manually closes the resource in a finally block. While this is correct management, it doesn't rely on the idiomatic way available to JDK 7 and above, allows for possible subtle problems, and complicates the reading of code by developers expecting the use of try-with-resources. </p> <p>Switch to using try with resources, as: <pre> try (InputStream is = getAStream()) { useTheStream(is); } </pre> ]]> </Details> </BugPattern> <BugPattern type="SSCU_SUSPICIOUS_SHADED_CLASS_USE"> <ShortDescription>Method calls a method from a class that has been shaded by a 3rdparty jar</ShortDescription> <LongDescription>Method {1} calls a method from a class that has been shaded by a 3rdparty jar</LongDescription> <Details> <![CDATA[ <p>This method calls a method found in a 3rd-party library, which appears to be shaded from another 3rd-party library. This occurs when a jar includes other code that uses tools like the maven shade plugin. It is likely you wanted to use the "first-class" class from the original jar, rather than the class with the shaded package structure, but your IDE pulled in the wrong import.</p> <p>An example might be, you attempted to use a method from the class: <pre><code> com.google.common.collect.Sets </code></pre> But instead, you import: <pre><code> org.apache.jena.ext.com.google.common.collect.Sets </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="USFW_UNSYNCHRONIZED_SINGLETON_FIELD_WRITES"> <ShortDescription>Method of Singleton class writes to a field in an unsynchronized manner</ShortDescription> <LongDescription>Method {1} of Singleton class writes to a field in an unsynchronized manner</LongDescription> <Details> <![CDATA[ <p>This method writes to a field of this class. Since this class is seen as a Singleton this can produce race conditions, or cause non-visible changes to other threads, because the field isn't accessed synchronously. ]]> </Details> </BugPattern> <BugPattern type="OI_OPTIONAL_ISSUES_USES_IMMEDIATE_EXECUTION"> <ShortDescription>Method uses immediate execution of a block of code that is often not used</ShortDescription> <LongDescription>Method {1} uses immediate execution of a block of code that is often not used</LongDescription> <Details> <![CDATA[ <p>This method uses the Optional.orElse() method passing in some code that will execute immediately, whether or not the else case of the Optional is needed. This may cause incorrect side effects to happen, or at the minimum, code to execute for no reason. It would be better to use Optional.orElseGet() ]]> </Details> </BugPattern> <BugPattern type="OI_OPTIONAL_ISSUES_USES_DELAYED_EXECUTION"> <ShortDescription>Method uses delayed execution of a block of code that is trivial</ShortDescription> <LongDescription>Method {1} uses immediate execution of a block of code that is trivial</LongDescription> <Details> <![CDATA[ <p>This method uses the Optional.orElseGet() method passing in a simple variable or constant value. As this value takes no time to execute and causes no side effects, the use of Optional.orElseGet is unnecessary and potentially confusing. You can use Optional.orElse() instead. ]]> </Details> </BugPattern> <BugPattern type="OI_OPTIONAL_ISSUES_CHECKING_REFERENCE"> <ShortDescription>Method checks an Optional reference for null</ShortDescription> <LongDescription>Method {1} checks an Optional reference for null</LongDescription> <Details> <![CDATA[ <p>This method compares an Optional reference variable against null. As the whole point of the Optional class is to avoid the null pointer exception, this use pattern is highly suspect. The code should always make sure the Optional reference is valid, and should count on the APIs of this class to check for the held reference instead. ]]> </Details> </BugPattern> <BugPattern type="OI_OPTIONAL_ISSUES_PRIMITIVE_VARIANT_PREFERRED"> <ShortDescription>Method uses a java.util.Optional when use of OptionalInt, OptionalLong, OptionalDouble would be more clear</ShortDescription> <LongDescription>Method {1} uses a java.util.Optional when use of OptionalInt, OptionalLong, OptionalDouble would be more clear</LongDescription> <Details> <![CDATA[ <p>This method creates an Optional object to hold an int, double or long. In these cases it is more natural to use the Optional variants OptionalInt, OptionalDouble and OptionalLong. </p> ]]> </Details> </BugPattern> <BugPattern type="OI_OPTIONAL_ISSUES_USES_ORELSEGET_WITH_NULL"> <ShortDescription>Method uses Optional.orElseGet(null)</ShortDescription> <LongDescription>Method {1} uses Optional.orElseGet(null)</LongDescription> <Details> <![CDATA[ <p>This method uses Optional.orElseGet(null). This method is supposed to to receive a lambda expression for what to execute when the Optional is not there. If you want to just return null, use Optional.orElse(null) instead. </p> ]]> </Details> </BugPattern> <BugPattern type="OI_OPTIONAL_ISSUES_ISPRESENT_PREFERRED"> <ShortDescription>Method uses Optional.equals(Optional.empty()), when Optional.isPresent is more readable</ShortDescription> <LongDescription>Method {1} uses Optional.equals(Optional.empty()), when Optional.isPresent is more readable</LongDescription> <Details> <![CDATA[ <p>This method uses Optional.equals(Optional.empty()). It is more readable and more clear just to use the Optional.isPresent() method to determine whether the reference exists or not. Use <br/> <pre><code> Optional f = getSomeOptional(); if (!f.isPresent()) { } </code></pre> rather than <br/> <pre><code> Optional f = getSomeOptional(); if (f.equals(Optional.empty()) { } </code></pre> </p> ]]> </Details> </BugPattern> <BugPattern type="UAC_UNNECESSARY_API_CONVERSION_DATE_TO_INSTANT"> <ShortDescription>Method constructs a Date object, merely to convert it to an Instant object</ShortDescription> <LongDescription>Method {1} constructs a Date object, merely to convert it to an Instant object</LongDescription> <Details> <![CDATA[ <p>This method creates a java.time.Instant object by first creating a java.util.Date object, and then calling toInstant() on it. It is simpler to just construct the Instant object directly, say by using {@code Instant.now()} to get the current time, of by using {@code Instant.parse(CharSequence)} to convert a String. </p> ]]> </Details> </BugPattern> <BugPattern type="UAC_UNNECESSARY_API_CONVERSION_FILE_TO_PATH"> <ShortDescription>Method constructs a File object, merely to convert it to a Path object</ShortDescription> <LongDescription>Method {1} constructs a File object, merely to convert it to a Path object</LongDescription> <Details> <![CDATA[ <p>This method creates a java.nio.file.Path object by first creating a java.io.File object, and then calling toPath() on it. It is simpler to just construct the Path object directly, say by using {@code Paths.get(String...)}. </p> ]]> </Details> </BugPattern> <BugPattern type="RFI_SET_ACCESSIBLE"> <ShortDescription>Method uses AccessibleObject.setAccessible to modify accessibility of classes</ShortDescription> <LongDescription>Method {1} uses AccessibleObject.setAccessible to modify accessibility of classes</LongDescription> <Details> <![CDATA[ <p>This method uses the reflective setAccessible method to alter the behavior of methods and fields in classes in ways that were not expected to be accessed by the author. Doing so circumvents the protections that the author provided through the class definition, and may expose your application to unexpected side effects and problems. This functionality is deprecated in Java 9, and in Java 10 it is expected that this functionality won't work at all. ]]> </Details> </BugPattern> <BugPattern type="AI_ANNOTATION_ISSUES_NEEDS_NULLABLE"> <ShortDescription>Method that can return null, is missing a @Nullable annotation</ShortDescription> <LongDescription>Method {1} that can return null, is missing a @Nullable annotation</LongDescription> <Details> <![CDATA[ <p>This method can return null, but is not annotated with an @Nullable annotation. Without this annotation, various IDEs, and static analysis tools may not be able to fully discover possible NullPointerExceptions in your code. By adding these annotations, you will discover problems around null-ness, more easily.</p> <p>Unfortunately there isn't just one @Nullable annotation, but this detector will recognize:</p> <ul> <li>org.jetbrains.annotations.Nullable</li> <li>javax.annotation.Nullable</li> <li>javax.annotation.CheckForNull</li> <li>edu.umd.cs.findbugs.annotations.Nullable</li> <li>org.springframework.lang.Nullable</li> <li>android.support.annotations.Nullable</li> </ul> <p> You can supply a comma separated list of classes that are custom Nullable Annotations if you desire, by using the system property -Dfb-contrib.ai.annotations="com.acme.Foo,com.acme.Boo" when run. ]]> </Details> </BugPattern> <BugPattern type="MUI_CALLING_SIZE_ON_SUBCONTAINER"> <ShortDescription>Method calls size() on a sub collection of a Map</ShortDescription> <LongDescription>Method {1} calls size() on a sub collection of a Map</LongDescription> <Details> <![CDATA[ <p>This method calls <code>size</code> on the keySet(), entrySet() or values() collections of a Map. These sub collections will have the same size as the base Map and so it is just simpler to call size on that Map. Calling size() on one of these sub collections will causes unnecessary allocations to occur. </p> ]]> </Details> </BugPattern> <BugPattern type="MUI_CONTAINSKEY_BEFORE_GET"> <ShortDescription>Method check a map with containsKey(), before using get()</ShortDescription> <LongDescription>Method {1} checks a map with containsKey(), before using get()</LongDescription> <Details> <![CDATA[ <p>This method checks for the presence of a key in a map using containsKey(), before attempting to fetch the value of the key using get(). This equates to doing two map lookups in a row. It is much simpler to just fetch the value with get, and checking for non null instead.</p> <p>As an example, instead of using <code> <pre> Map<String, String> myMap = getSomeMap(); if (myMap.containsKey("foo")) { String value = myMap.get("foo"); .... } </pre> </code> convert this to <code> <pre> Map<String, String> myMap = getSomeMap(); String value = myMap.get("foo"); if (value != null) { .... } </pre> </code> </p> <p>The only caveat to this is that if you use a null value in a map to represent a third state for the key, then in this case using containsKey is 'correct'. This means an entry found in the map with a null value is taken differently than no entry at all. However, this is a very subtle programming paradigm, and likely to cause problems. If you wish to mark an entry as not being present, it is better to use a named 'sentinel' value to denote this, so instead of: <code> <pre> Map<String, String> myMap = getSomeMap(); if (myMap.containsKey("foo")) { String value = myMap.get("foo"); .... } </pre> </code> convert this to <code> <pre> Map<String, String> myMap = getSomeMap(); String value = myMap.get("foo"); if (NOT_FOUND.equals(value)) { .... } where NOT_FOUND is some constant that denotes this special status. Of course you will need to find a special sentinel value for each type you are using that isn't possible to have normally. </pre> </code> </p> ]]> </Details> </BugPattern> <BugPattern type="MUI_GET_BEFORE_REMOVE"> <ShortDescription>Method gets an item from a map with get(), before using remove()</ShortDescription> <LongDescription>Method {1} gets an item from a map with get(), before using remove()</LongDescription> <Details> <![CDATA[ <p>This method fetches the value of an entry in a map using get(K k), and then follows it up with a remove(K k). Since a remove() also returns the value, there is no point for doing the get, and just causes two map lookups to occur when it can be done with just one.</p> <p>As an example, instead of using <code> <pre> Map<String, String> myMap = getSomeMap(); String v = myMap.get("foo")) { myMap.remove("foo"); </pre> </code> convert this to <code> <pre> Map<String, String> myMap = getSomeMap(); String v = myMap.remove("foo"); </pre> </code> </p> ]]> </Details> </BugPattern> <BugPattern type="LUI_USE_SINGLETON_LIST"> <ShortDescription>Method builds a list from one element using Arrays.asList</ShortDescription> <LongDescription>Method {1} builds a list from one element using Arrays.asList rather than Collections.singletonList</LongDescription> <Details> <![CDATA[ <p>This method builds a list using Arrays.asList(foo), passing in a single element. Arrays.asList needs to first create an array from this one element, and then build a List that wraps this array. It is simpler to use Collections.singletonList(foo), which does not create the array, and produces a far simpler instance of List. Since both of these arrays are immutable (from the List's point of view) they are equivalent from a usage standpoint. </p> <p>There is one difference between Array.asList and Collections.singletonList that you should be mindful of. The rarely used set(index, value) method is allowed to be used with a List created by Array.asList, but not with Collections.singletonList. So if you do use the set(index, value) method continue using Arrays.asList. ]]> </Details> </BugPattern> <BugPattern type="LUI_USE_GET0"> <ShortDescription>Method uses collection streaming to get first item in a List</ShortDescription> <LongDescription>Method {1} uses collection streaming to get first item in a List</LongDescription> <Details> <![CDATA[ <p>This method fetches the first item in a List using collection streaming. As a list is already ordered there is no need to do that, just use the regular get(0) interface.<br/> Example: <code><pre> String s = myList.stream().findFirst().get(); </pre></code> Can be more simply done using <code><pre> String s = myList.get(0); </pre></code> </p> ]]> </Details> </BugPattern> <BugPattern type="LUI_USE_COLLECTION_ADD"> <ShortDescription>Method passes a temporary one item list to Collection.addAll()</ShortDescription> <LongDescription>Method {1} passes a temporary one item list to Collection.addAll()</LongDescription> <Details> <![CDATA[ <p>This method creates a temporary list using Collections.singletonList, or Arrays.asList with one element in it, and then turns around and calls the addAll() method on another collection. Since you are only adding one element to the collection, it is simpler to just call the add(object) method on the collection you are using and by pass creating the intermediate List.</p> ]]> </Details> </BugPattern> <BugPattern type="FII_AVOID_CONTAINS_ON_COLLECTED_STREAM"> <ShortDescription>Method calls contains() on a collected lambda expression</ShortDescription> <LongDescription>Method {1} calls contains() on a collected lambda expresssion</LongDescription> <Details> <![CDATA[ <p>This method builds a collection using lambda expressions with a collect terminal operation. It then immediately calls the contains() method on it, to see if an item is present. This is sub optimal as the lambda still needs to build the entire collection, iterating the entire source list. It is better to use anyMatch() to short circuit the building of the collection. </p> <p> Instead of <code><pre> baubles.stream().map(Bauble::getName).collect(Collectors.toSet()).contains(name) </pre></code> do <code></pre> baubles.stream().anyMatch(b -> name.equals(b.getName())) </pre></code> </p> ]]> </Details> </BugPattern> <BugPattern type="FII_USE_METHOD_REFERENCE"> <ShortDescription>Method creates an anonymous lambda expression instead of specifying a method reference</ShortDescription> <LongDescription>Method {1} creates an anonymous lamda expression instead of specifying a method reference</LongDescription> <Details> <![CDATA[ <p>This method defines an anonymous lambda function to be called to fetch a single value from the passed in value. While this will work, it is needlessly complex as this function merely calls a single getter method on the object, and thus the code can be simplied by just passing in a method reference instead.</p> <p> Instead of <code><pre> baubles.stream().map(b -> b.getName()).collect(Collectors.toSet()) </pre></code> do <code></pre> baubles.stream().map(Bauble::getName).collect(Collectors.toSet()) </pre></code> </p> ]]> </Details> </BugPattern> <BugPattern type="FII_USE_ANY_MATCH"> <ShortDescription>Method suboptimally finds any match in a stream</ShortDescription> <LongDescription>Method {1} suboptimally finds any match in a stream</LongDescription> <Details> <![CDATA[ <p>This method looks for one item in a stream using filter().findFirst.isPresent() when .anyMatch() will do the same thing more succintly</p> ]]></Details> </BugPattern> <BugPattern type="FII_USE_FIND_FIRST"> <ShortDescription>Method collects a List from a stream() just to get the first element</ShortDescription> <LongDescription>Method {1} collects a List from a stream() just to get the first element</LongDescription> <Details> <![CDATA[ <p>This method streams data into a List just to call get(0) to get the first item. You can just use findFirst() to short circuit the processing of the stream.</p> <p> Instead of <code><pre> baubles.stream().collect(Collectors.toList()).get(0) </pre></code> do <code></pre> baubles.stream().findFirst().get()) </pre></code> </p> ]]> </Details> </BugPattern> <BugPattern type="FII_COMBINE_FILTERS"> <ShortDescription>Method implements a stream using back to back filters</ShortDescription> <LongDescription>Method {1} implements a stream using back to back filters</LongDescription> <Details> <![CDATA[ <p>This method streams data using more than one filter back to back. These can just be combined into one filter</p> ]]> </Details> </BugPattern> <BugPattern type="FII_USE_FUNCTION_IDENTITY"> <ShortDescription>Method declares an identity lambda function rather than using Function.identity()</ShortDescription> <LongDescription>Method {1} declares an identity lambda function rather than using Function.identity()</LongDescription> <Details> <![CDATA[ <p>This method declares a no-op (identity) lambda method rather than just specifying Function.identity()</p> ]]> </Details> </BugPattern> <BugPattern type="FII_AVOID_SIZE_ON_COLLECTED_STREAM"> <ShortDescription>Method calls size() on a collected lambda expression</ShortDescription> <LongDescription>Method {1} calls size() on a collected lambda expresssion</LongDescription> <Details> <![CDATA[ <p>This method builds a collection using lambda expressions with a collect terminal operation. It then immediately calls the size() method on it, to get a count of items. This is sub optimal as the lambda still needs to build the entire collection, iterating the entire source list. It is better to use count() predicate to short circuit the building of the collection. If you were using a Set, then also add the distinct() predicate. </p> <p> Instead of <code><pre> baubles.stream().filter(b -> b.getName("orb")).collect(Collectors.toList()).size()) </pre></code> do <code></pre> baubles.stream().filter(b -> b.getName("orb")).count() </pre></code> or for sets you can use <code></pre> baubles.stream().filter(b -> b.getName("orb")).distinct().count() </pre></code> </p> ]]> </Details> </BugPattern> <BugPattern type="SUI_CONTAINS_BEFORE_ADD"> <ShortDescription>Method checks for an item in a set with contains, before using add()</ShortDescription> <LongDescription>Method {1} checks for an item in a set with contains, before using add()</LongDescription> <Details> <![CDATA[ <p>This method checks to see if an element is not in a set before adding it. This is unnecessary as you can just add the item, and if the item exists, it won't add it, otherwise it will.</p> <p>As an example, instead of using <code> <pre> Set<String> mySet = getSomeSet(); if (!mySet.contains("foo")) { mySet.add("foo"); } </pre> </code> convert this to <code> <pre> Set<String> mySet = getSomeSet(); if (mySet.add("foo")) { } </pre> </code> </p> ]]> </Details> </BugPattern> <BugPattern type="SUI_CONTAINS_BEFORE_REMOVE"> <ShortDescription>Method checks for an item in a set with contains, before using remove()</ShortDescription> <LongDescription>Method {1} checks for an item in a set with contains, before using remove()</LongDescription> <Details> <![CDATA[ <p>This method checks to see if an element is in a set before removing it. This is unnecessary as you can just remove the item, and if the item exists, it will return true.</p> <p>As an example, instead of using <code> <pre> Set<String> mySet = getSomeSet(); if (mySet.contains("foo")) { mySet.remove("foo"); } </pre> </code> convert this to <code> <pre> Set<String> mySet = getSomeSet(); if (mySet.remove("foo")) { } </pre> </code> </p> ]]> </Details> </BugPattern> <BugPattern type="SAT_SUSPICIOUS_ARGUMENT_TYPES"> <ShortDescription>This method invokes a method with parameters that seem incorrect for their intended use</ShortDescription> <LongDescription>This method {1} invokes a method with parameters that seem incorrect for their intended use</LongDescription> <Details> <![CDATA[ <p>This method calls a method passing arguments that seem incorrect for the intended purpose of the method. Make sure that the argument types are valid</p> <ul> <li><p>For Match.hasEntry it seems unlikely you want to pass a Matcher and non-Matcher at the same time</p></li> </ul> ]]> </Details> </BugPattern> <BugPattern type="ENMI_EQUALS_ON_ENUM"> <ShortDescription>Method calls equals on an enum instance</ShortDescription> <LongDescription>Method {1} calls equals on an enum instance</LongDescription> <Details> <![CDATA[ <p>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.</p> ]]> </Details> </BugPattern> <BugPattern type="ENMI_NULL_ENUM_VALUE"> <ShortDescription>Method sets an enum reference to null</ShortDescription> <LongDescription>Method {1} sets an enum reference to null</LongDescription> <Details> <![CDATA[ <p>This method sets the value of an enum reference to null. An enum should never have a null value. If there is a state where you do not know what the value of an enum should be, than that should be one of the proper enum value. So add a MyEnum.UNKNOWN or such. This keeps the logic of switch statements, etc, much simpler. ]]> </Details> </BugPattern> <BugPattern type="ENMI_ONE_ENUM_VALUE"> <ShortDescription>Enum class only declares one enum value</ShortDescription> <LongDescription>Enum class {0} only declares one enum value</LongDescription> <Details> <![CDATA[ <p>This enum class only declares one value (or perhaps 0!). As such it is pointless, as its value will always be the same thing. Therefore use of this enum is just bloating the code base. One exception is if you are using a null value as a second value. This is a mistake, and should be replaced with a second enum value, even if it's NULL, or UNKNOWN, or NON_INTITIALIZED or some other sentinel value. ]]> </Details> </BugPattern> <BugPattern type="AKI_SUPERFLUOUS_ROUTE_SPECIFICATION"> <ShortDescription>Method specifies superfluous routes thru route() or concat()</ShortDescription> <LongDescription>Method {1} specifies superfluous routes thru route() or concat()</LongDescription> <Details> <![CDATA[ <p>This method uses the route() or concat() method to build optional routes but only passes 1 route to the method. This just causes an extra route specification to be created for no reason. Only use route() or concat() when you have more than one route to combine into one. ]]> </Details> </BugPattern> <BugPattern type="PKI_SUPERFLUOUS_ROUTE_SPECIFICATION"> <ShortDescription>Method specifies superfluous routes thru route() or concat()</ShortDescription> <LongDescription>Method {1} specifies superfluous routes thru route() or concat()</LongDescription> <Details> <![CDATA[ <p>This method uses the route() or concat() method to build optional routes but only passes 1 route to the method. This just causes an extra route specification to be created for no reason. Only use route() or concat() when you have more than one route to combine into one. ]]> </Details> </BugPattern> <!-- BugCode --> <BugCode abbrev="ISB">Inefficient String Buffering</BugCode> <BugCode abbrev="SCI">Synchronized Collection Iterators</BugCode> <BugCode abbrev="CC">Cyclomatic Complexity</BugCode> <BugCode abbrev="OCP">Overly Concrete Parameters</BugCode> <BugCode abbrev="LII">List Indexed Iterating</BugCode> <BugCode abbrev="UCC">Unrelated Collection Contents</BugCode> <BugCode abbrev="DRE">Declared Runtime Exception</BugCode> <BugCode abbrev="CE">Class Envy</BugCode> <BugCode abbrev="LSC">Literal String Comparison</BugCode> <BugCode abbrev="PCOA">Partially Constructed Object Access</BugCode> <BugCode abbrev="DLC">Dubious List Collection</BugCode> <BugCode abbrev="PL">Parallel Lists</BugCode> <BugCode abbrev="FP">Final Parameters</BugCode> <BugCode abbrev="ACEM">Abstract Class Empty Methods</BugCode> <BugCode abbrev="MAC">Manual Array Copy</BugCode> <BugCode abbrev="FPL">Floating Point Loops</BugCode> <BugCode abbrev="NCMU">Non Collection Method Use</BugCode> <BugCode abbrev="CAO">Confusing Autoboxed Overloading</BugCode> <BugCode abbrev="AFBR">Abnormal Finally Block Return</BugCode> <BugCode abbrev="SMII">Static Method Instance Invocation</BugCode> <BugCode abbrev="STS">Spurious Thread States</BugCode> <BugCode abbrev="NAB">Needless Autoboxing</BugCode> <BugCode abbrev="USBR">Unnecessary Store Before Return</BugCode> <BugCode abbrev="COM">Copied Overridden Method</BugCode> <BugCode abbrev="ABC">Array Based Collection</BugCode> <BugCode abbrev="ODN">Orphaned DOM Node</BugCode> <BugCode abbrev="AOM">Abstract Overridden Method</BugCode> <BugCode abbrev="CBX">Custom Built XML</BugCode> <BugCode abbrev="BSB">Bloated Synchronized Block</BugCode> <BugCode abbrev="CLI">Constant List Index</BugCode> <BugCode abbrev="SCR">Sloppy Class Reflection</BugCode> <BugCode abbrev="AWCBR">Array Wrapped Call By Reference</BugCode> <BugCode abbrev="SG">Sluggish GUI</BugCode> <BugCode abbrev="NIR">Needless Instance Retrieval</BugCode> <BugCode abbrev="DDC">Double Date comparison</BugCode> <BugCode abbrev="SWCO">Suspicious Wait on Concurrent Object</BugCode> <BugCode abbrev="JVR">JDBC Vendor Reliance</BugCode> <BugCode abbrev="PMB">Possible Memory Bloat</BugCode> <BugCode abbrev="LSYC">Local Synchronized Collection</BugCode> <BugCode abbrev="FCBL">Field Could Be Local</BugCode> <BugCode abbrev="NOS">Non Owned Synchronization</BugCode> <BugCode abbrev="NRTL">Non Recycleable Taglib</BugCode> <BugCode abbrev="S508C">Section 508 Compliance Violations</BugCode> <BugCode abbrev="UEC">Use Enum Collections</BugCode> <BugCode abbrev="SIL">SQL In Loop</BugCode> <BugCode abbrev="NMCS">Needless Member Collection Synchronization</BugCode> <BugCode abbrev="ITC">Inheritance Type Checking</BugCode> <BugCode abbrev="SACM">Static Array Created in Method</BugCode> <BugCode abbrev="PRMC">Possibly Redundant Method Calls</BugCode> <BugCode abbrev="UTA">Use toArray</BugCode> <BugCode abbrev="LEST">Lost Exception Stack Trace</BugCode> <BugCode abbrev="UCPM">Use Character Parameterized Method</BugCode> <BugCode abbrev="TR">Tail Recursion</BugCode> <BugCode abbrev="URV">Unrelated Return Values</BugCode> <BugCode abbrev="PIS">Possible Incomplete Serialization</BugCode> <BugCode abbrev="SCRV">Suspicious Comparator Return Values</BugCode> <BugCode abbrev="SPP">Sillyness Pot Pourri</BugCode> <BugCode abbrev="BAS">Bloated Assignment Scope</BugCode> <BugCode abbrev="SCII">Spoiled Child Interface Implementor</BugCode> <BugCode abbrev="DWI">Deleting While Iterating</BugCode> <BugCode abbrev="USS">Use String Split</BugCode> <BugCode abbrev="SJVU">Suspicious JDK Version Use</BugCode> <BugCode abbrev="UAA">Use Add All</BugCode> <BugCode abbrev="MRC">Method Returns Constant</BugCode> <BugCode abbrev="NCS">Needless Custom Serialization</BugCode> <BugCode abbrev="MOM">Misleading Overload Model</BugCode> <BugCode abbrev="EXS">Exception Softening</BugCode> <BugCode abbrev="CFS">Confusing Function Semantics</BugCode> <BugCode abbrev="UTAO">Unit Test Assertion Oddities</BugCode> <BugCode abbrev="SCA">Suspicious Clone Algorithm</BugCode> <BugCode abbrev="WEM">Weak Exception Messaging</BugCode> <BugCode abbrev="SCSS">Suspicious Clustered Session Support</BugCode> <BugCode abbrev="LO">Logger Oddities</BugCode> <BugCode abbrev="IICU">Incorrect Internal Class use</BugCode> <BugCode abbrev="DSOC">Dubious Set of Collections</BugCode> <BugCode abbrev="BED">Bogus Exception Declaration</BugCode> <BugCode abbrev="UNNC">Unnecessary New Null Check</BugCode> <BugCode abbrev="DTEP">Deprecated Typesafe Enum Pattern</BugCode> <BugCode abbrev="TBP">Tristate Boolean Pattern</BugCode> <BugCode abbrev="SUA">Suspicious Uninitialized Array</BugCode> <BugCode abbrev="ITU">Inappropriate toString Use</BugCode> <BugCode abbrev="IKNC">Inconsistent Key Name Casing</BugCode> <BugCode abbrev="OC">Overzealous Casting</BugCode> <BugCode abbrev="PDP">Poorly Defined Parameter</BugCode> <BugCode abbrev="NSE">Non Symmetric Equals</BugCode> <BugCode abbrev="CVAA">Contravariant Array Assignment</BugCode> <BugCode abbrev="NFF">Non Functional Field</BugCode> <BugCode abbrev="SNG">Suspicious Null Guard</BugCode> <BugCode abbrev="MDM">More Dumb Methods</BugCode> <BugCode abbrev="ROOM">Reflection on Object Methods</BugCode> <BugCode abbrev="IPU">Improper Properties use</BugCode> <BugCode abbrev="PCAIL">Possible Constant Allocation In Loop</BugCode> <BugCode abbrev="WOC">Write Only Collection</BugCode> <BugCode abbrev="UVA">Use Var Args</BugCode> <BugCode abbrev="PUS">Possible Unsuspected Serialization</BugCode> <BugCode abbrev="SEC">Side Effect Constructor</BugCode> <BugCode abbrev="SGSU">Suspicious Getter Setter Use</BugCode> <BugCode abbrev="LGO">Lingering Graphics Object</BugCode> <BugCode abbrev="STB">Stacked Try Blocks</BugCode> <BugCode abbrev="CEBE">Commons EqualsBuilder To Equals</BugCode> <BugCode abbrev="CHTH">Commons HashCodeBuilder To hashCode</BugCode> <BugCode abbrev="CSBTS">Commons ToStringBuilder To String</BugCode> <BugCode abbrev="CCNE">Compare class name equals</BugCode> <BugCode abbrev="BRPI">Backport concurrent reuse of public identifiers</BugCode> <BugCode abbrev="CU">Clone Usability</BugCode> <BugCode abbrev="CAAL">Confusing Array asList</BugCode> <BugCode abbrev="PSC">Presize Collection</BugCode> <BugCode abbrev="UMTP">Unbound Method Template Parameter</BugCode> <BugCode abbrev="NPMC">Non Productive Method Call</BugCode> <BugCode abbrev="AIOB">Array Index Out of Bounds</BugCode> <BugCode abbrev="ICA">Invalid Constant Argument</BugCode> <BugCode abbrev="CNC">Collection Naming Confusion</BugCode> <BugCode abbrev="PME">Poor Mans Enum</BugCode> <BugCode abbrev="UP">Unused Parameter</BugCode> <BugCode abbrev="FCCD">Find Class Circular Dependencies</BugCode> <BugCode abbrev="MUC">Modifying Unmodifiable Collection</BugCode> <BugCode abbrev="UJM">Unjitable method</BugCode> <BugCode abbrev="HES">Hanging ExecutorService</BugCode> <BugCode abbrev="HCP">HttpClient Problems</BugCode> <BugCode abbrev="CTU">Conflicting Time Units</BugCode> <BugCode abbrev="CSI">Charset Issues</BugCode> <BugCode abbrev="CBC">Contains Based Conditional</BugCode> <BugCode abbrev="OPM">Overly Permissive Method</BugCode> <BugCode abbrev="STT">Stringified Types</BugCode> <BugCode abbrev="SLS">Suspicious Loop Search</BugCode> <BugCode abbrev="CRF">Conflating Resources And Files</BugCode> <BugCode abbrev="IMC">Immature Class</BugCode> <BugCode abbrev="JXI">JAX-RS Issues</BugCode> <BugCode abbrev="JPAI">JPA Issues</BugCode> <BugCode abbrev="SEO">Suboptimal Expression Order</BugCode> <BugCode abbrev="IOI">IO Issues</BugCode> <BugCode abbrev="DMC">Dubious Map Collection</BugCode> <BugCode abbrev="BL">Burying Logic</BugCode> <BugCode abbrev="WI">Wiring issues</BugCode> <BugCode abbrev="CCI">Concurrent Collection Issues</BugCode> <BugCode abbrev="UTWR">Use Try With Resources</BugCode> <BugCode abbrev="SSCU">Suspicious Shaded Class Use</BugCode> <BugCode abbrev="USFW">Unsynchronized Singleton Field Writes</BugCode> <BugCode abbrev="OI">Optional Issues</BugCode> <BugCode abbrev="UAC">Unnecessary Api Conversion</BugCode> <BugCode abbrev="RFI">Reflection Issues</BugCode> <BugCode abbrev="AI">Annotation Issues</BugCode> <BugCode abbrev="MUI">Map Usage Issues</BugCode> <BugCode abbrev="LUI">List Usage Issues</BugCode> <BugCode abbrev="FII">FunctionalInterface Issues</BugCode> <BugCode abbrev="SUI">Set Usage Issues</BugCode> <BugCode abbrev="SAT">Suspicious Argument Types</BugCode> <BugCode abbrev="ENMI">Enum Issues</BugCode> <BugCode abbrev="AKI">Akka Issues</BugCode> <BugCode abbrev="PKI">Pekko Issues</BugCode> </MessageCollection>