# Use Guard Condition
# Description
Replaces, when possible, the last if-statement of a method body with a guard-if and unwraps its body.
# Benefits
Reduces the cognitive complexity of a method.
# Tags
# Code Changes
# Void method ending with an if statement
Pre
public void voidMethod() {
doSomething("whatever");
if(numericCondition() > 0) {
doSomething("Should create guard condition with less");
doSomething("Should transform");
}
}
Post
public void voidMethod() {
doSomething("whatever");
if (numericCondition() <= 0) {
return;
}
doSomething("Should create guard condition with less");
doSomething("Should transform");
}
# Method with return type
Pre
public int methodWithReturnType() {
doSomething("whatever");
if(condition()) {
doSomething("Should be moved out of the if");
doSomething("should transform");
return 1;
}
return 0;
}
Post
public int methodWithReturnType() {
doSomething("whatever");
if (!condition()) {
return 0;
}
doSomething("Should be moved out of the if");
doSomething("should transform");
return 1;
}
# Limitations
# Multiple if-then-else branches
Pre
public void multipleElseBranches() {
if(numericCondition() > 0) {
doSomething("Should create guard condition with less");
doSomething("Should not transform");
} else if(numericCondition() == 0) {
doSomething("on else-if branch");
} else {
doSomething("Else branch");
}
}
Post
public void multipleElseBranches() {
if(numericCondition() > 0) {
doSomething("Should create guard condition with less");
doSomething("Should not transform");
} else if(numericCondition() == 0) {
doSomething("on else-if branch");
} else {
doSomething("Else branch");
}
}
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.