Master recipe template — every element
org.openrewrite.example.MasterRecipeTemplateorg.openrewrite.recipe:rewrite-static-analysisA styling reference that exercises every UI element a recipe detail page can render: inline code, tags, options, a composite Definition, “Used by”, examples (parameters, unchanged context, multi-language, new file, and diffs), all Usage variants, and data tables. This is not a real recipe — real recipes are subsets of these elements.
Definition
- Recipe list
- YAML
- Constructors of an
abstractclass should not be declaredpublic - Atomic Boolean, Integer, and Long equality checks compare their values
new BigDecimal(double)should not be usedBigDecimalrounding 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 - 'Collection.toArray()' should be passed an array of the proper type
- Covariant equals
- Default comes last
- Remove empty blocks
- Equals avoids null
- Explicit initialization
Externalizableclasses have no-arguments constructor- Finalize private fields
- Fall through
- Finalize classes with private constructors
- Fix
String#formatandString#formattedexpressions forloop counters incremented in update- Use
indexOf(String, int) indexOf()replaceable bycontains()indexOfshould not compare greater than zero- Inline variable
- Use
Collection#isEmpty()instead of comparingsize() - Simplify lambda blocks to expressions
- Standardize method name casing
switchstatements should have at least 3caseclauses- Modifier order
- No multiple variable declarations
- Fix missing braces
- Nested enums are not static
- Change
StringBuilderandStringBuffercharacter constructor argument toString - No double brace initialization
- Use
Collections#emptyList(),emptyMap(), andemptySet() - Use comparison rather than equality checks in for conditions
- Remove
finalize()method - No primitive wrappers for #toString() or #compareTo(..)
- Jump statements should not be redundant
- Unnecessary
String#toString - Unnecessary
String#valueOf(..) finalize()calls super- Prefer
System.getProperty("user.home")overSystem.getenv("HOME") - Use primitive wrapper
valueOfmethod - Redundant file creation
- Remove extra semicolons
- Remove redundant null checks before instanceof
- Remove redundant null checks before literal equals
- Rename methods named
hashcode,equal, ortostring - Replace
A.class.isInstance(a)witha instanceof A - Use method references in lambda
- Replace
StringBuilder#appendwithString - Replace String concatenation with
String.valueOf() - Simplify
Arrays.asList(..)with varargs - Simplify boolean expression
- Simplify boolean return
- Static methods need not be final
- Use
String.equals()onStringliterals - Unnecessary close in try-with-resources
- Unnecessary explicit type arguments
- Remove unnecessary parentheses
- Remove
@Nullableand@CheckForNullannotations from primitives - Unnecessary
returnas last statement in void method - Upper case literal suffixes
- Use the diamond operator
- No C-style array declarations
- Use %n instead of \n in format strings
- Prefer
whileoverforloops - Write octal values as decimal
- Structural equality tests should use
==or!= itshouldn't be used as a lambda parameter name- Replace
Char#toInt()withChar#code - Order imports
---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.staticanalysis.CommonStaticAnalysis
displayName: Common static analysis issues
description: |
Resolve common static analysis issues (also known as SAST issues).
preconditions:
- org.openrewrite.Singleton
recipeList:
- org.openrewrite.staticanalysis.AbstractClassPublicConstructor
- org.openrewrite.staticanalysis.AtomicPrimitiveEqualsUsesGet
- org.openrewrite.staticanalysis.BigDecimalDoubleConstructorRecipe
- org.openrewrite.staticanalysis.BigDecimalRoundingConstantsToEnums
- org.openrewrite.staticanalysis.BooleanChecksNotInverted
- org.openrewrite.staticanalysis.CaseInsensitiveComparisonsDoNotChangeCase
- org.openrewrite.staticanalysis.CatchClauseOnlyRethrows
- org.openrewrite.staticanalysis.ChainStringBuilderAppendCalls
- org.openrewrite.staticanalysis.CollectionToArrayShouldHaveProperType
- org.openrewrite.staticanalysis.CovariantEquals
- org.openrewrite.staticanalysis.DefaultComesLast
- org.openrewrite.staticanalysis.EmptyBlock
- org.openrewrite.staticanalysis.EqualsAvoidsNull
- org.openrewrite.staticanalysis.ExplicitInitialization
- org.openrewrite.staticanalysis.ExternalizableHasNoArgsConstructor
- org.openrewrite.staticanalysis.FinalizePrivateFields
- org.openrewrite.staticanalysis.FallThrough
- org.openrewrite.staticanalysis.FinalClass
- org.openrewrite.staticanalysis.FixStringFormatExpressions
- org.openrewrite.staticanalysis.ForLoopIncrementInUpdate
- org.openrewrite.staticanalysis.IndexOfChecksShouldUseAStartPosition
- org.openrewrite.staticanalysis.IndexOfReplaceableByContains
- org.openrewrite.staticanalysis.IndexOfShouldNotCompareGreaterThanZero
- org.openrewrite.staticanalysis.InlineVariable
- org.openrewrite.staticanalysis.IsEmptyCallOnCollections
- org.openrewrite.staticanalysis.LambdaBlockToExpression
- org.openrewrite.staticanalysis.MethodNameCasing
- org.openrewrite.staticanalysis.MinimumSwitchCases
- org.openrewrite.staticanalysis.ModifierOrder
- org.openrewrite.staticanalysis.MultipleVariableDeclarations
- org.openrewrite.staticanalysis.NeedBraces
- org.openrewrite.staticanalysis.NestedEnumsAreNotStatic
- org.openrewrite.staticanalysis.NewStringBuilderBufferWithCharArgument
- org.openrewrite.staticanalysis.NoDoubleBraceInitialization
- org.openrewrite.staticanalysis.NoEmptyCollectionWithRawType
- org.openrewrite.staticanalysis.NoEqualityInForCondition
- org.openrewrite.staticanalysis.NoFinalizer
- org.openrewrite.staticanalysis.NoPrimitiveWrappersForToStringOrCompareTo
- org.openrewrite.staticanalysis.NoRedundantJumpStatements
- org.openrewrite.staticanalysis.NoToStringOnStringType
- org.openrewrite.staticanalysis.NoValueOfOnStringType
- org.openrewrite.staticanalysis.ObjectFinalizeCallsSuper
- org.openrewrite.staticanalysis.PreferSystemGetPropertyOverGetenv
- org.openrewrite.staticanalysis.PrimitiveWrapperClassConstructorToValueOf
- org.openrewrite.staticanalysis.RedundantFileCreation
- org.openrewrite.staticanalysis.RemoveExtraSemicolons
- org.openrewrite.staticanalysis.RemoveRedundantNullCheckBeforeInstanceof
- org.openrewrite.staticanalysis.RemoveRedundantNullCheckBeforeLiteralEquals
- org.openrewrite.staticanalysis.RenameMethodsNamedHashcodeEqualOrToString
- org.openrewrite.staticanalysis.ReplaceClassIsInstanceWithInstanceof
- org.openrewrite.staticanalysis.ReplaceLambdaWithMethodReference
- org.openrewrite.staticanalysis.ReplaceStringBuilderWithString
- org.openrewrite.staticanalysis.ReplaceStringConcatenationWithStringValueOf
- org.openrewrite.staticanalysis.SimplifyArraysAsList
- org.openrewrite.staticanalysis.SimplifyBooleanExpression
- org.openrewrite.staticanalysis.SimplifyBooleanReturn
- org.openrewrite.staticanalysis.StaticMethodNotFinal
- org.openrewrite.staticanalysis.StringLiteralEquality
- org.openrewrite.staticanalysis.UnnecessaryCloseInTryWithResources
- org.openrewrite.staticanalysis.UnnecessaryExplicitTypeArguments
- org.openrewrite.staticanalysis.UnnecessaryParentheses
- org.openrewrite.staticanalysis.UnnecessaryPrimitiveAnnotations
- org.openrewrite.staticanalysis.UnnecessaryReturnAsLastStatement
- org.openrewrite.staticanalysis.UpperCaseLiteralSuffixes
- org.openrewrite.staticanalysis.UseDiamondOperator
- org.openrewrite.staticanalysis.UseJavaStyleArrayDeclarations
- org.openrewrite.staticanalysis.UsePortableNewlines
- org.openrewrite.staticanalysis.WhileInsteadOfFor
- org.openrewrite.staticanalysis.WriteOctalValuesAsDecimal
- org.openrewrite.kotlin.cleanup.EqualsMethodUsage
- org.openrewrite.kotlin.cleanup.ImplicitParameterInLambda
- org.openrewrite.kotlin.cleanup.ReplaceCharToIntWithCode
- org.openrewrite.java.OrderImports
Used by
This recipe is used as part of the following composite recipes (from the open-source catalog):
- Common static analysis issues
- Code cleanup
- Migrate to Java 21
- Migrate to Java 17
- Spring Boot 3.x migration
- Spring Boot 2.x migration
- JUnit 4 to JUnit 5
- Migrate to Jakarta EE 10
- Find and fix vulnerable dependencies
- Remove unused imports
- Apache Commons Lang 2.x to 3.x
- Migrate to Mockito 5.x
- Modernize logging with SLF4J
- Replace Guava with Java equivalents
- Static analysis fixes (SAST)
- Migrate to AssertJ
- Spring Framework 6.x migration
- Migrate to Quarkus 3
- Best practices for Java
- Security best practices
Examples
java
MasterRecipeTest#withParameters| Parameter | Value |
|---|---|
| includeTestSources | true |
- java
- Diff
class A {
final String a = "value";
final String b = "value";
final String c = "value";
}
class A {
private static final String VALUE = "value";
final String a = VALUE;
final String b = VALUE;
final String c = VALUE;
}
@@ -1,4 +1,4 @@
class A {
- final String a = "value";
- final String b = "value";
+ private static final String VALUE = "value";
+ final String a = VALUE;
+ final String b = VALUE;
}
pom.xml
MasterRecipeTest#withUnchangedContextproject
- pom.xml
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
</project>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<properties>
<java.version>21</java.version>
</properties>
</project>
java, properties
MasterRecipeTest#multiLanguage- java
- Diff
class A {
boolean b = !(a == b);
}
class A {
boolean b = a != b;
}
@@ -1,3 +1,3 @@
class A {
- boolean b = !(a == b);
+ boolean b = a != b;
}
- properties
- Diff
spring.profiles=dev
spring.config.activate.on-profile=dev
@@ -1,1 +1,1 @@
-spring.profiles=dev
+spring.config.activate.on-profile=dev
toml
MasterRecipeTest#createsNewFile- toml
[tool.poetry]
name = "my-project"
version = "0.1.0"
description = "A sample project"
java
MasterRecipeTest#simplifyBoolean- java
- Diff
class A {
boolean b = a == true;
}
class A {
boolean b = a;
}
@@ -1,3 +1,3 @@
class A {
- boolean b = a == true;
+ boolean b = a;
}
java
MasterRecipeTest#removeUnusedImport- java
- Diff
import java.util.List;
class A {
}
class A {
}
@@ -1,4 +1,2 @@
-import java.util.List;
-
class A {
}
Usage
Java / JVM
This recipe has no required configuration options. Users of Moderne can run it via the Moderne CLI.
You will need to have configured the Moderne CLI on your machine before you can run the following command.
mod run . --recipe MasterRecipeTemplate
If the recipe is not available locally, then you can install it using:
mod config recipes jar install org.openrewrite.recipe:rewrite-static-analysis:2.36.0
With configuration
You will need to have configured the Moderne CLI on your machine before you can run the following command.
mod run . --recipe MasterRecipeTemplate --recipe-option "methodPattern=java.util.List add(..)"
If the recipe is not available locally, then you can install it using:
mod config recipes jar install org.openrewrite.recipe:rewrite-static-analysis:2.36.0
JavaScript
In order to run JavaScript recipes, you will need to use the Moderne CLI. For JavaScript specific configuration instructions, please see our configuring JavaScript guide.
Once the CLI is installed, you can install this JavaScript recipe package by running the following command:
mod config recipes npm install @openrewrite/recipe-static-analysis
Then, you can run the recipe via:
mod run . --recipe org.openrewrite.example.MasterRecipeTemplate
Python
In order to run Python recipes, you will need to use the Moderne CLI.
Once the CLI is installed, you can install this Python recipe package by running the following command:
mod config recipes pip install openrewrite-recipe-static-analysis
Then, you can run the recipe via:
mod run . --recipe org.openrewrite.example.MasterRecipeTemplate
C#
In order to run C# recipes, you will need to use the Moderne CLI.
Once the CLI is installed, you can install this C# recipe package by running the following command:
mod config recipes nuget install OpenRewrite.Recipe.StaticAnalysis
Then, you can run the recipe via:
mod run . --recipe org.openrewrite.example.MasterRecipeTemplate
See how this recipe works across thousands of OSS repositories
Run this recipe at scale on the Moderne Platform and review every change before it lands.
Data tables
Source files that had results
org.openrewrite.table.SourcesFileResultsSource files that were modified by the recipe run.
| Column | Description |
|---|---|
| Source path before the run | The source path of the file before the run. null when a source file was created during the run. |
| Source path after the run | A recipe may modify the source path. This is the path after the run. null when a source file was deleted during the run. |
| Parent of the recipe that made changes | In a hierarchical recipe, the parent of the recipe that made a change. Empty if this is the root of a hierarchy or if the recipe is not hierarchical at all. |
| Recipe that made changes | The specific recipe that made a change. |
| Estimated time saving | An estimated effort that a developer to fix manually instead of using this recipe, in unit of seconds. |
| Cycle | The recipe cycle in which the change was made. |
Source files that had search results
org.openrewrite.table.SearchResultsSearch results that were found during the recipe run.
| Column | Description |
|---|---|
| Source path of search result before the run | The source path of the file with the search result markers present. |
| Source path of search result after run the run | A recipe may modify the source path. This is the path after the run. null when a source file was deleted during the run. |
| Result | The trimmed printed tree of the LST element that the marker is attached to. |
| Description | The content of the description of the marker. |
| Recipe that added the search marker | The specific recipe that added the Search marker. |
Source files that errored on a recipe
org.openrewrite.table.SourcesFileErrorsThe details of all errors produced by a recipe run.
| Column | Description |
|---|---|
| Source path | The file that failed to parse. |
| Recipe that made changes | The specific recipe that made a change. |
| Stack trace | The stack trace of the failure. |
Recipe performance
org.openrewrite.table.RecipeRunStatsStatistics used in analyzing the performance of recipes.
| Column | Description |
|---|---|
| The recipe | The recipe whose stats are being measured both individually and cumulatively. |
| Source file count | The number of source files the recipe ran over. |
| Source file changed count | The number of source files which were changed in the recipe run. Includes files created, deleted, and edited. |
| Cumulative scanning time (ns) | The total time spent across the scanning phase of this recipe. |
| Max scanning time (ns) | The max time scanning any one source file. |
| Cumulative edit time (ns) | The total time spent across the editing phase of this recipe. |
| Max edit time (ns) | The max time editing any one source file. |
Structured datain <head> — not rendered on the page
This SoftwareSourceCode JSON-LD is injected into the page’s<head> and is invisible to readers in production — it’s shown here only so you can see the markup.
{
"@context": "https://schema.org",
"@type": "SoftwareSourceCode",
"name": "Master recipe template — every element",
"identifier": "org.openrewrite.example.MasterRecipeTemplate",
"description": "A styling reference that exercises every UI element a recipe detail page can render: inline code, tags, options, a composite Definition, “Used by”, examples (parameters, unchanged context, multi-language, new file, and diffs), all Usage variants, and data tables. This is not a real recipe — real recipes are subsets of these elements.",
"codeRepository": "https://github.com/openrewrite/rewrite-static-analysis",
"programmingLanguage": [
"Java",
"Kotlin",
"Properties",
"YAML"
],
"license": "https://docs.moderne.io/licensing/moderne-source-available-license"
}