1.使用return
2.使用switch
3.使用三目运算
4.使用枚举
5.使用多态
6.使用jdk1.9新特性
1.使用return(常用)
优化前代码:
-
if ("java".equals(str)) {
-
// 业务代码......
-
} else {
-
return;
-
}
优化后代码:
-
if (!"java".equals(str)) {
-
return;
-
}
2.使用三目运算(常用)
3.使用枚举
优化前代码
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;
}
优化后代码
public enum TypeEnum {
Name(1), Age(2), Address(3);
public Integer typeId;
TypeEnum(Integer typeId) {
this.typeId = typeId;
}
}
4.使用jdk1.9新特性
从 JDK 1.8 开始引入 Optional 类,在 JDK 9 时对 Optional 类进行了改进,增加了 ifPresentOrElse() 方法,我们可以借助它,来消除 if else 的判断,使用如下。
优化前代码:
String str = "java";
if (str == null) {
System.out.println("Null");
} else {
System.out.println(str);
}
优化后代码:
Optional<String> opt = Optional.of("java");
opt.ifPresentOrElse(v ->
System.out.println(v), () -> System.out.println("Null"));
5.梳理优化判断逻辑
和第 4 点比较类似,我们可以通过分析 if else 的逻辑判断语义,写出更加易懂的代码,例如以下这个嵌套判断的优化。
优化前代码:
// 年龄大于 18
if (age > 18) {
// 工资大于 5000
if (salary > 5000) {
// 是否漂亮
if (pretty == true) {
return true;
}
}
}
return false;
优化后代码:
if (age < 18) {
return false;
}
if (salary < 5000) {
return false;
}
return pretty;
6.使用switch(常用)
7.使用多态
优化前代码:
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;
}
优化后代码
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;
}
}
调用
IType itype = (IType) Class.forName("com.example." + type).newInstance();
Integer typeId = itype.getType();
参考链接:
https://blog.csdn.net/a754315344/article/details/107104490?utm_source=app