# 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");
}
}
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.