# Collapse If Statements
# Description
Collapses, when possible, the nested if-statements into a single one by concatenating their conditions with the infix operator &&
.
If the concatenation results to an infix expression with more than two components, then a new local variable is introduced to store the condition.
# Benefits
Improves the readability by reducing the number of the nested language constructs.
# Tags
# Code Changes
# Simple collapse
Pre
if (a) {
if (b) {
System.out.println("Ok");
}
}
Post
if (a && b) {
System.out.println("Ok");
}
# Collapsing more than two statements
Pre
if (a) {
if (b) {
if (c) {
System.out.println("Ok");
}
}
}
Post
boolean condition = a && b && c;
if (condition) {
System.out.println("Ok");
}
# Compound conditions
Pre
if (a) {
if (b || c) {
System.out.println("Ok");
}
}
Post
boolean condition = a && (b || c);
if (condition) {
System.out.println("Ok");
}
You Want To Have Those Changes Done Automatically?
The automatic application of this rule is supported in the following jSparrow versions: