优化if-else代码的八种方案
前言
代码中如果if-else比较多,阅读起来比较困难,维护起来也比较困难,很容易出bug,接下来,本文将介绍优化if-else代码的八种方案。
优化方案一:提前return,去除不必要的else
如果if-else代码块包含return语句,可以考虑通过提前return,把多余else干掉,使代码更加优雅。
优化前:
if (condition) {
//doSomething
} else {
return;
}
if(!condition){
return;
}
//doSomething
优化方案二:使用条件三目运算符
int price;
if (condition) {
price = 80;
} else {
price = 100;
}
int price = condition ? 80 : 100;
优化方案三:使用枚举
String OrderStatusDes;
if (orderStatus == 0) {
OrderStatusDes = "订单未支付";
} elseif ( OrderStatus == 1 ) {
OrderStatusDes = "订单已支付";
} elseif ( OrderStatus == 2 ) {
OrderStatusDes = "已发货";
}
...
public enum OrderStatusEnum {
UN_PAID(0, "订单未支付"),
PAIDED(1, "订单已支付"),
SENDED(2, "已发货"),
;
private int index;
private String desc;
public int getIndex() {
return index;
}
public String getDesc() {
return desc;
}
OrderStatusEnum(int index, String desc) {
this.index = index;
this.desc = desc;
}
OrderStatusEnum of(int orderStatus) {
for (OrderStatusEnum temp : OrderStatusEnum.values()) {
if (temp.getIndex() == orderStatus) {
return temp;
}
}
return null;
}
}
String OrderStatusDes = OrderStatusEnum.0f(orderStatus).getDesc();
优化方案四:合并条件表达式
double getVipDiscount () {
if (age < 18) {
return 0.8;
}
if ("深圳".equals(city)) {
return 0.8;
}
if (isStudent) {
return 0.8;
}
//do somethig
}
double getVipDiscount(){
if (age< 18 || "深圳".equals(city)||isStudent){
return 0.8;
}
//doSomthing
}
优化方案五:使用 Optional
String str = "jay@huaxiao";
if (str != null) {
System.out.println(str);
} else {
System.out.println("Null");
}
Optional<String> strOptional = Optional.of("jay@huaxiao");
strOptional.ifPresentOrElse(System.out::println, () -> System.out.println("Null"));
优化方案六:表驱动法
if (param.equals(value1)) {
doAction1(someParams);
} else if (param.equals(value2)) {
doAction2(someParams);
} else if (param.equals(value3)) {
doAction3(someParams);
}
// ...
Map, Function> action> actionMappings = new HashMap<>();
// 这里泛型 ? 是为方便演示,实际可替换为你需要的类型
// 初始化
actionMappings.put(value1, (someParams) -> {
doAction1(someParams)
});
actionMappings.put(value2, (someParams) -> {
doAction2(someParams)
});
actionMappings.put(value3, (someParams) -> {
doAction3(someParams)
});
// 省略多余逻辑语句
actionMappings.get(param).apply(someParams);
优化方案七:优化逻辑结构,让正常流程走主干
public double getAdjustedCapital () {
if (_capital <= 0.0) {
return 0.0;
}
if (_intRate > 0 && _duration > 0) {
return (_income / _duration) * ADJ_FACTOR;
}
return 0.0;
}
public double getAdjustedCapital () {
if (_capital <= 0.0) {
return 0.0;
}
if (_intRate <= 0 || _duration <= 0) {
return 0.0;
}
return (_income / _duration) * ADJ_FACTOR;
}
优化方案八:策略模式+工厂方法消除if else
String medalType = "guest";
if ("guest".equals(medalType)) {
System.out.println("嘉宾勋章");
} else if ("vip".equals(medalType)) {
System.out.println("会员勋章");
} else if ("guard".equals(medalType)) {
System.out.println("展示守护勋章");
}
...
//勋章接口
public interface IMedalService {
void showMedal ();
String getMedalType ();
}
//守护勋章策略实现类
public class GuardMedalServiceImpl implements IMedalService {
public void showMedal() {
System.out.println("展示守护勋章");
}
public String getMedalType() {
return "guard";
}
}
//嘉宾勋章策略实现类
public class GuestMedalServiceImpl implements IMedalService {
public void showMedal() {
System.out.println("嘉宾勋章");
}
public String getMedalType() {
return "guest";
}
}
//VIP勋章策略实现类
public class VipMedalServiceImpl implements IMedalService {
public void showMedal() {
System.out.println("会员勋章");
}
public String getMedalType() {
return "vip";
}
}
//勋章服务工产类
public class MedalServicesFactory {
private static final Map
map = new HashMap<>();
static {
map.put("guard", new GuardMedalServiceImpl());
map.put("vip", new VipMedalServiceImpl());
map.put("guest", new GuestMedalServiceImpl());
}
public static IMedalService getMedalService(String medalType) {
return map.get(medalType);
}
}
...
public class Test {
public static void main(String[] args) {
String medalType = "guest";
IMedalService medalService = MedalServicesFactory.getMedalService(medalType);
medalService.showMedal();
}
}
参考与感谢
6个实例详解如何把if-else代码重构成高质量代码 如何 “干掉” if...else
有道无术,术可成;有术无道,止于术
欢迎大家关注Java之道公众号
好文章,我在看❤️
评论