# if-else代码优化的八种方案

2019/04/10 10:10

## 前言

### 优化方案一：提前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 ="订单未支付";
}else if(OrderStatus==1){
OrderStatusDes ="订单已支付";
}else if(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();
}


//守护勋章策略实现类
public class GuardMedalServiceImpl implements IMedalService {
@Override
public void showMedal() {
System.out.println("展示守护勋章");
}
}
//嘉宾勋章策略实现类
public class GuestMedalServiceImpl implements IMedalService {
@Override
public void showMedal() {
System.out.println("嘉宾勋章");
}
}
//VIP勋章策略实现类
public class VipMedalServiceImpl implements IMedalService {
@Override
public void showMedal() {
System.out.println("会员勋章");
}
}


//勋章服务工产类
public class MedalServicesFactory {

private static final Map<String, IMedalService> 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();
}
}


## 个人公众号

• 觉得写得好的小伙伴给个点赞+关注啦，谢谢~
• 同时非常期待小伙伴们能够关注我公众号，后面慢慢推出更好的干货~嘻嘻

0
0 收藏

0 评论
0 收藏
0