Static analysis and remediation
Remediations for issues identified by SAST tools.
Categories
Composite Recipes
Recipes that include further recipes, often including the individual recipes below.
- Code cleanup
- Common static analysis issues
- Modernize
BufferedWritercreation & prevent file descriptor leaks - Replace
org.apache.commons.lang3.Validate#notNullwithObjects#requireNonNull - Replace
org.apache.commons.lang3.Validate#notNullwithObjects#requireNonNull - Simplify ternary expressions
- URL Equals and Hash Code
Recipes
- 'Collection.toArray()' should be passed an array of the proper type
- Add
@Serialannotation toserialVersionUID - Add missing
@Overrideto overriding and implementing methods - Add
serialVersionUIDto aSerializableclass when missing - Annotate methods which may return
nullwith@Nullable - Annotate null-checked method parameters with
@Nullable - Annotate required method parameters with
@NonNull - Atomic Boolean, Integer, and Long equality checks compare their values
- Avoid boxed boolean expressions
BigDecimalrounding constants toRoundingModeenums- Boolean checks should not be inverted
- CaseInsensitive comparisons do not alter case
- Catch clause should do more than just rethrow
- Chain
StringBuilder.append()calls - Chain calls to builder methods
- Change
StringBuilderandStringBuffercharacter constructor argument toString - Changes code to use Java 17's
instanceofpattern matching - Combine semantically equal catch blocks
- Constructors of an
abstractclass should not be declaredpublic - Control flow statement indentation
- Convert
new BufferedWriter(new FileWriter(File))toFiles.newBufferedWriter(Path) - Convert
new BufferedWriter(new FileWriter(File, boolean))toFiles.newBufferedWriter(Path, StandardOpenOption) - Convert
new BufferedWriter(new FileWriter(String))toFiles.newBufferedWriter(Path) - Convert
new BufferedWriter(new FileWriter(String, boolean))toFiles.newBufferedWriter(Path, StandardOpenOption) - Convert
while (true)with initialifbreak to loop condition - Covariant equals
- Custom import order
- Default comes last
- Don't use final on local variables
- Enum values should be compared with "=="
- Equals avoids null
- Explicit initialization
Externalizableclasses have no-arguments constructor- Fall through
- Finalize classes with private constructors
- Finalize local variables
- Finalize method arguments
- Finalize private fields
- Fix
String#formatandString#formattedexpressions - Fix missing braces
- Hidden field
- Hide utility class constructor
- Inline variable
- Java API best practices
- Jump statements should not be redundant
- Mask credit card numbers
- Modifier order
- Move
@Nullablemethod annotations to the return type - Nested enums are not static
- No C-style array declarations
- No double brace initialization
- No multiple variable declarations
- No primitive wrappers for #toString() or #compareTo(..)
- Operator wrapping
- Prefer
System.getProperty("user.home")overSystem.getenv("HOME") - Prefer direct comparison of numbers
- Prefer increment/decrement and compound assignment operators
- Prefer
whileoverforloops - Properly use declaration-site type variance
- Properly use declaration-site type variance for well-known types
- Redundant file creation
- Reformat local variable names to camelCase
- Reformat private field names to camelCase
- Remove
@Nullableand@CheckForNullannotations from primitives - Remove JavaDoc
@param,@return, and@throwswith no description - Remove
Object.finalize()invocations - Remove
System.out#printlnstatements - Remove author tags from JavaDocs
- Remove catch for a checked exception if the try block does not throw that exception
- Remove empty blocks
- Remove extra semicolons
- Remove
finalize()method - Remove garbage collection invocations
- Remove redundant casts
- Remove redundant null checks before instanceof
- Remove redundant null checks before literal equals
- Remove
toString()calls on arrays - Remove unnecessary parentheses
- Remove unneeded assertions
- Remove unneeded block
- Remove unused local variables
- Remove unused private fields
- Remove unused private methods
- Removes from code Java 14's
instanceofpattern matching - Rename caught exceptions in empty catch blocks to
ignored - Rename methods named
hashcode,equal, ortostring - Rename packages to lowercase
- Reorder annotation attributes alphabetically
- Reorder annotations alphabetically
- Replace
A.class.isInstance(a)witha instanceof A - Replace
Optional#isPresent()withOptional#ifPresent() - Replace String concatenation with
String.valueOf() - Replace
StringBuilder#appendwithString - Replace
booleanExpression ? false : truewith!booleanExpression - Replace
booleanExpression ? true : falsewithbooleanExpression - Replace calls to
Thread.run()withThread.start() - Replace
catch(Exception)with specific declared exceptions thrown in the try block - Replace deprecated
Runtime#exec()methods - Replace duplicate
Stringliterals - Replace invocations of
Collections#sort(List, Comparator)withList#sort(Comparator) - Replace
java.util.Set#removeAll(java.util.Collection)withjava.util.Collection#forEach(Set::remove) - Replace
java.util.Stackwithjava.util.Deque - Replace
org.apache.commons.lang3.Validate#notNullwithObjects#requireNonNull - Replace redundant String format invocations that are wrapped with PrintStream operations
- Replace referential equality operators with Object equals method invocations when the operands both override
Object.equals(Object obj) - Replace text block with regular string
- Replaces
Object.notify()withObject.notifyAll() - Set charset encoding explicitly when calling
String#getBytes - Simplify
Arrays.asList(..)with varargs - Simplify boolean expression
- Simplify boolean expressions using De Morgan's laws
- Simplify boolean return
- Simplify compound statement
- Simplify consecutive assignments
- Simplify constant if branch execution
- Simplify
elsebranch if it only has a singleif - Simplify
java.time.Durationunits - Simplify lambda blocks to expressions
- Sorted set stream should be collected to LinkedHashSet
- Standardize method name casing
- Static methods need not be final
- Ternary operators should not be nested
- Typecast parenthesis padding
- URL Equals
- URL Hash Code
- Unnecessary
String#toString - Unnecessary
String#valueOf(..) - Unnecessary close in try-with-resources
- Unnecessary explicit type arguments
- Unnecessary
returnas last statement in void method - Unnecessary throws
- Unwrap
@Repeatableannotations - Unwrap else block after return or throw statement
- Upper case literal suffixes
- Use %n instead of \n in format strings
- Use
Collectioninterfaces - Use
Collection#isEmpty()instead of comparingsize() - Use
Collections#emptyList(),emptyMap(), andemptySet() - Use Empty Array for
Collection.toArray() - Use
Map#containsKey - Use
StandardCharsetconstants - Use
String.contentEquals(CharSequence)instead ofString.equals(CharSequence.toString()) - Use
String.equals()onStringliterals - Use
String::replace()when first parameter is not a real regular expression - Use
System.lineSeparator() - Use comparison rather than equality checks in for conditions
- Use explicit types on lambda arguments
- Use
indexOf(String, int) - Use lambda expressions instead of anonymous classes
- Use method references in lambda
- Use primitive wrapper
valueOfmethod - Use the diamond operator
- Week Year (YYYY) should not be used for date formatting
- Write octal values as decimal
finalize()calls superforloop counters incremented in updateforloop counters should use postfix operatorshashCode()should not be called on array instancesindexOfshould not compare greater than zeroindexOf()replaceable bycontains()new BigDecimal(double)should not be usedswitchstatements should have at least 3caseclauses