Optimization rules - provided by PMD
Optimization
LocalVariableCouldBeFinal
A local variable assigned only once can be declared final.
MethodArgumentCouldBeFinal
A method argument that is never re-assigned within the method can be declared final.
AvoidInstantiatingObjectsInLoops
New objects created within loops should be checked to see if they can created outside them and reused.
UseArrayListInsteadOfVector
ArrayList is a much better Collection implementation than Vector if thread-safe operation is not required.
SimplifyStartsWith
Since it passes in a literal of length 1, calls to (string).startsWith can be rewritten using (string).charAt(0) at the expense of some readability.
UseStringBufferForStringAppends
The use of the '+=' operator for appending strings causes the JVM to create and use an internal StringBuffer.If a non-trivial number of these concatenations are being used then the explicit use of a StringBuilder or threadsafe StringBuffer is recommended to avoid this.
UseArraysAsList
The java.util.Arrays class has a "asList" method that should be used when you want to create a new List from an array of objects.
It is faster than executing a loop to copy all the elements of the array one by one.
AvoidArrayLoops
Instead of manually copying data between two arrays, use the efficient System.arraycopy method instead.
UnnecessaryWrapperObjectCreation
Most wrapper classes provide static conversion methods that avoid the need to create intermediate objects just to create the primitive forms.
Using these avoids the cost of creating objects that also need to be garbage-collected later.
AddEmptyString
The conversion of literals to strings by concatenating them with empty strings is inefficient.
It is much better to use one of the type-specific toString() methods instead.
RedundantFieldInitializer
Java will initialize fields with known default values so any explicit initialization of those same defaultsis redundant and results in a larger class file (approximately three additional bytecode instructions per field).
PrematureDeclaration
Checks for variables that are defined before they might be used.
A reference is deemed to be premature if it is created right before a block of code that doesn't use it that also has the ability to return or throw an exception.
String and StringBuffer/StringBuilder
AvoidDuplicateLiterals
Code containing duplicate String literals can usually be improved by declaring the String as a constant field.
StringInstantiation
Avoid instantiating String objects; this is usually unnecessary since they are immutable and can be safely shared.
StringToString
Avoid calling toString() on objects already known to be string instances; this is unnecessary.
InefficientStringBuffering
Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate buffers willneed to be be created and destroyed by the JVM.
UnnecessaryCaseChange
Using equalsIgnoreCase() is faster than using toUpperCase / toLowerCase().equals()
UseStringBufferLength
Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals("")orStringBuffer.toString().length() == ...
AppendCharacterWithChar
Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods.
ConsecutiveLiteralAppends
Consecutively calling StringBuffer/StringBuilder.append with String literals
UseIndexOfChar
Use String.indexOf(char) when checking for the index of a single character; it executes faster.
InefficientEmptyStringCheck
String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String object just to check its size.
Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found.
InsufficientStringBufferDeclaration
Failing to pre-size a StringBuffer or StringBuilder properly could cause it to re-size many timesduring runtime.
This rule attempts to determine the total number the characters that are actually passed into StringBuffer.append(), but represents a best guess "worst case" scenario.
An empty StringBuffer/StringBuilder constructor initializes the object to 16 characters. This defaultis assumed if the length of the constructor can not be determined.
UselessStringValueOf
No need to call String.valueOf to append to a string; just use the valueOf() argument directly.
StringBufferInstantiationWithChar
Individual character values provided as initialization arguments will be converted into integers.
This can lead to internal buffer sizes that are larger than expected.
Some examples
new StringBuffer() // 16
new StringBuffer(6) // 6
new StringBuffer("hello world") // 11 + 16 = 27
new StringBuffer('A') // chr(A) = 65
new StringBuffer("A") // 1 + 16 = 17
new StringBuilder() // 16
new StringBuilder(6) // 6
new StringBuilder("hello world") // 11 + 16 = 27
new StringBuilder('C') // chr(C) = 67
new StringBuilder("A") // 1 + 16 = 17
UseEqualsToCompareStrings
Using '==' or '!=' to compare strings only works if intern version is used on both sides.
Use the equals() method instead.
AvoidStringBufferField
StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaksif held within objects with long lifetimes.
Code Size
NPathComplexity
The NPath complexity of a method is the number of acyclic execution paths through that method.
A threshold of 200 is generally considered the point where measures should be taken to reduce complexity and increase readability.
ExcessiveMethodLength
When methods are excessively long this usually indicates that the method is doing more than its name/signature might suggest.
They also become challenging for others to digest since excessive scrolling causes readers to lose focus.
Try to reduce the method length by creating helper methods and removing any copy/pasted code.
ExcessiveParameterList
Methods with numerous parameters are a challenge to maintain, especially if most of them share thesame datatype.
These situations usually denote the need for new objects to wrap the numerous parameters.
ExcessiveClassLength
Excessive class file lengths are usually indications that the class may be burdened with excessive responsibilities that could be provided by external classes or functions.
In breaking these methodsapart the code becomes more managable and ripe for reuse.
CyclomaticComplexity
Complexity directly affects maintenance costs is determined by the number of decision points in a method plus one for the method entry.
The decision points include 'if', 'while', 'for', and 'case labels' calls.
Generally, numbers ranging from 1-4 denote low complexity, 5-7 denote moderate complexity, 8-10 denotehigh complexity, and 11+ is very high complexity.
ExcessivePublicCount
Classes with large numbers of public methods and attributes require disproportionate testing effortssince combinational side effects grow rapidly and increase risk.
Refactoring these classes intosmaller ones not only increases testability and reliability but also allows new variations to bedeveloped easily.
TooManyFields
Classes that have too many fields can become unwieldy and could be redesigned to have fewer fields,possibly through grouping related fields in new objects.
For example, a class with individual city/state/zip fields could park them within a single Address field.
NcssMethodCount
This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of linesof code for a given method.
NCSS ignores comments, and counts actual statements.
Using this algorithm, lines of code that are split are counted as one.
NcssTypeCount
This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of linesof code for a given type.
NCSS ignores comments, and counts actual statements. Using this algorithm,lines of code that are split are counted as one.
NcssConstructorCount
This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of linesof code for a given constructor. NCSS ignores comments, and counts actual statements.
Using this algorithm,lines of code that are split are counted as one.
TooManyMethods
A class with too many methods is probably a good suspect for refactoring, in order to reduce its complexity and find a way tohave more fine grained objects.
Migration (Java)
ReplaceVectorWithList
Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe operations are not required.
ReplaceHashtableWithMap
Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required.
ReplaceEnumerationWithIterator
Consider replacing Enumeration usages with the newer java.util.Iterator
AvoidEnumAsIdentifier
Use of the term 'enum' will conflict with newer versions of Java since it is a reserved word.
AvoidAssertAsIdentifier
Use of the term 'assert' will conflict with newer versions of Java since it is a reserved word.
IntegerInstantiation
Calling new Integer() causes memory allocation that can be avoided by the static Integer.valueOf().
It makes use of an internal cache that recycles earlier instances making it more memory efficient.
ByteInstantiation
Calling new Byte() causes memory allocation that can be avoided by the static Byte.valueOf().
It makes use of an internal cache that recycles earlier instances making it more memory efficient.
ShortInstantiation
Calling new Short() causes memory allocation that can be avoided by the static Short.valueOf().
It makes use of an internal cache that recycles earlier instances making it more memory efficient.
LongInstantiation
Calling new Long() causes memory allocation that can be avoided by the static Long.valueOf().
It makes use of an internal cache that recycles earlier instances making it more memory efficient.
Coupling
CouplingBetweenObjects
This rule counts the number of unique attributes, local variables, and return types within an object.
A number higher than the specified threshold can indicate a high degree of coupling.
ExcessiveImports
A high number of imports can indicate a high degree of coupling within an object.
This rule counts the number of unique imports and reports a violation if the count is above the user-specified threshold.
LooseCoupling
The use of implementation types as object references limits your ability to use alternate implementations in the future as requirements change.
Whenever available, referencing objects by their interface types provides much more flexibility.
LoosePackageCoupling
Avoid using classes from the configured package hierarchy outside of the package hierarchy, except when using one of the configured allowed classes.
LawOfDemeter
The Law of Demeter is a simple rule, that says "only talk to friends".
It helps to reduce coupling between classes or objects.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.