灵活使用return
List<Integer> list = extraList();
if (list != null) {
list.add(1);
// ....
}
通过尽早使用 return 返回,可以有效减少代码缩进层级,简化控制流,尤其在处理多层嵌套逻辑时提升可读性。
List<Integer> list = extraList();
if (list == null){
return;
}
list.add(1);
// ....
优化复杂条件表达式的可读性
当一个条件表达式的条件很长时,第一时间会很难去理解这段代码需要表达什么,我们可以引入局部变量的方式去优化这段代码:
if (index > 100 || index % 2 == 0 || index % 3 == 0 || index % 4 == 0){
}
通过将表达式拆分,这样就能够有效避免在审查或维护时忽略关键逻辑,也让每个条件更易理解。
boolean condition1 = index > 100;
boolean condition2 = index % 2 == 0;
boolean condition3 = index % 3 == 0;
boolean condition4 = index % 4 == 0;
if (condition1 || condition2 || condition3 || condition4){
}
优化避免空指针的获取逻辑
在下面的链式调用中,每个都可能会抛出空指针,最常规的用法我们会使用 if 嵌套去获取最终值,但是这样的可读性非常差
String name = person.getProvince().getCity().getDistrict().getName();
if (person != null){
Province province = person.getProvince();
if (province != null){
City city = province.getCity();
if (city != null){
District district = city.getDistrict();
if (district != null){
name = district.getName();
}
}
}
}
这时我们可以引入 Optional 去优化这段代码的可读性
String name = Optional.ofNullable(person)
.map(Person::getProvince)
.map(Province::getCity)
.map(City::getDistrict)
.map(District::getName)
.orElse("");