9 Proven Ways to Eliminate Excessive if‑else in Java Code
This article examines why overusing if‑else statements makes Java code hard to read and presents nine practical techniques—including early returns, maps, ternary operators, combined conditions, enums, Optional, streamlined logic, polymorphism, and switch statements—to refactor and simplify conditional logic for cleaner, more maintainable code.
If‑else is one of the most frequently used keywords in programming, but excessive use can make code painful to read. This article offers nine methods to reduce or eliminate redundant if‑else constructs in Java.
1. Use early return
Replace unnecessary else branches with early returns.
Before:
if (str.equals("java")) {
// business code !
true;
} else {
return ;
}After:
if (str.equals("java")) {
return ;
}
return false;2. Use a Map
Store related decision data in a map to avoid multiple if‑else checks.
Before:
if (t == 1) {
type = "name";
} else if (t == 2) {
type = "id";
} else if (t == 3) {
type = "mobile";
}Define a map:
Map<Integer, String> typeMap = new HashMap<>();
typeMap.put(1, "name");
typeMap.put(2, "id");
typeMap.put(3, "mobile");Then replace the whole block with a single line:
type = typeMap.get(ty);3. Use the ternary operator
Condense simple if‑else assignments.
Before:
Integer score = 81;
if (score > 80) {
score = 100;
} else {
score = 60;
}After:
score = score > 80 ? 100 : 60;4. Combine condition expressions
Merge multiple related checks into a single logical expression.
Before:
String city = "西安";
String area = "029";
String province = "陕西";
if ("西安".equals(city)) {
return "xi'an";
}
if ("029".equals(area)) {
return "xi'an";
}
if ("陕西".equals(province)) {
return "xi'an";
}After:
if ("西安".equals(city) || "029".equals(area) || "陕西".equals(province)) {
return "xi'an";
}5. Use enum
Replace string‑based conditionals with an enumeration.
Before:
Integer typeId = 0;
String type = "Name";
if ("Name".equals(type)) {
typeId = 1;
} else if ("Age".equals(type)) {
typeId = 2;
} else if ("Address".equals(type)) {
typeId = 3;
}Define an enum:
public enum TypeEnum {
Name(1), Age(2), Address(3);
public Integer typeId;
TypeEnum(Integer typeId) {
this.typeId = typeId;
}
}Usage:
typeId = TypeEnum.valueOf("Name").typeId;6. Use Optional
Leverage Optional (JDK 9+) to avoid explicit null checks.
Before:
String str = "java";
if (str == null) {
System.out.println("Null");
} else {
System.out.println(str);
}After:
Optional<String> opt = Optional.of("java");
opt.ifPresentOrElse(v ->
System.out.println(v),
() -> System.out.println("Null"));Tip: This requires JDK 9 or higher.
7. Refine logical flow
Rewrite nested conditions to a flat, early‑return style.
Before:
// age > 18
if (age > 18) {
// salary > 5000
if (salary > 5000) {
// pretty?
if (pretty == true) {
return true;
}
}
}
return false;After:
if (age < 18) {
return false;
}
if (salary < 5000) {
return false;
}
return pretty == true;8. Apply polymorphism
Encapsulate varying behavior in subclasses instead of if‑else.
Before:
Integer typeId = 0;
String type = "Name";
if ("Name".equals(type)) {
typeId = 1;
} else if ("Age".equals(type)) {
typeId = 2;
} else if ("Address".equals(type)) {
typeId = 3;
}Define an interface and implementations:
public interface IType {
public Integer getType();
}
public class Name implements IType {
@Override
public Integer getType() { return 1; }
}
public class Age implements IType {
@Override
public Integer getType() { return 2; }
}
public class Address implements IType {
@Override
public Integer getType() { return 3; }
}Usage:
IType itype = (IType) Class.forName("com.example." + type).newInstance();
Integer typeId = itype.getType();Note: In real projects the interface and classes should be placed in separate files.
9. Prefer switch where appropriate
When the condition checks a single variable against constants, a switch can be clearer and faster.
If‑else version:
if (cmd.equals("add")) {
result = n1 + n2;
} else if (cmd.equals("subtract")) {
result = n1 - n2;
} else if (cmd.equals("multiply")) {
result = n1 * n2;
} else if (cmd.equals("divide")) {
result = n1 / n2;
} else if (cmd.equals("modulo")) {
result = n1 % n2;
}Switch version (Java 8):
switch (cmd) {
case "add":
result = n1 + n2;
break;
case "subtract":
result = n1 - n2;
break;
case "multiply":
result = n1 * n2;
break;
case "divide":
result = n1 / n2;
break;
case "modulo":
result = n1 % n2;
break;
}Arrow‑style switch (Java 14):
switch (cmd) {
case "add" -> { result = n1 + n2; }
case "subtract" -> { result = n1 - n2; }
case "multiply" -> { result = n1 * n2; }
case "divide" -> { result = n1 / n2; }
case "modulo" -> { result = n1 % n2; }
}By applying these techniques, developers can write more concise, readable, and maintainable Java code, turning repetitive if‑else ladders into elegant solutions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
