Home  >  Article  >  Java  >  How to write if-else elegantly in Java

How to write if-else elegantly in Java

WBOY
WBOYforward
2023-04-29 22:04:191506browse

1. switch

The switch method has good effects on enumeration value processing. For example, different processing needs to be done for different order statuses, because the status values ​​are limited, then we can use switch directly. To do different processing for different states:

Original statement

public void before(Integer status) {
        if(status == 1){
            System.out.println("订单未接单");
        }else if(status == 2){
            System.out.println("订单未发货");
        }else if(status == 3){
            System.out.println("订单未签收");
        }else{
            System.out.println("订单已签收");
        }
    }

switch

public void greater(Integer status) {
        switch (status){
            case 1:
                System.out.println("订单未接单");
                break;
            case 2:
                System.out.println("订单未发货");
                break;
            case 3:
                System.out.println("订单未签收");
                break;
            default:
                System.out.println("订单已签收");
        }
    }

Summary:

switch statement is suitable for limited judgment conditions and no need After complex calculations, handle scenarios with simple statements. If our judgment conditions require a series of complex calculations, or the processing statement logic is relatively complex, we have to consider other processing methods. After all, writing a lot of processing statements in the case is not comfortable. Things

2. Functional interface

When dealing with more complex processing logic, we prefer to separate these processing logics separately, rather than still processing them in one method, adding The overall readability and decoupling are also the patterns we derived from using functional interfaces to process if else

The essence of functional interface map processing if else is to extract the complex processing logic of each condition separately It is a functional interface method that calls different methods through unified judgment conditions. The specific examples are as follows

@Component
public class FunctionInterfaceStrategy {

    /**
     * key 方法参数,多个参数可以自定义一个实体类处理
     * value 方法返回值
     */
    private Map<Integer, Function<Object,Boolean>> operationMap;

    @PostConstruct
    private void init(){
        operationMap = new HashMap<>();
        operationMap.put(1,this::takeOrder);
        operationMap.put(2,this::sendOrder);
        operationMap.put(3,this::signOrder);
        operationMap.put(4,this::finishOrder);
    }

    public Boolean doOperation(Object params,Integer status){
        return operationMap.get(status) == null || operationMap.get(status).apply(params);
    }

    private Boolean takeOrder(Object params){
        // TODO 比较复杂的处理逻辑
        System.out.println("订单未接单");
        return true;
    }

    private Boolean sendOrder(Object params){
        // TODO 比较复杂的处理逻辑
        System.out.println("订单未发货");
        return true;
    }

    private Boolean signOrder(Object params){
        // TODO 比较复杂的处理逻辑
        System.out.println("订单未签收");
        return true;
    }

    private Boolean finishOrder(Object params){
        // TODO 比较复杂的处理逻辑
        System.out.println("订单已签收");
        return true;
    }

}

When calling, there is no need to use if else to distinguish, directly pass in the parameters to the function map and call

   @Autowired
    private FunctionInterfaceStrategy functionInterfaceStrategy;
    
    
    functionInterfaceStrategy.doOperation("参数",1);

Of course, what we demonstrated above is a functional interface with parameters and return values. In actual production, we may also need other forms of functional interfaces. We will list them separately for your reference.

Interface name Description Calling method
Supplier No parameters, There is a return value get
Consumer There are parameters, no return value accept
Runnable No parameters, no return value run
Function With parameters, there is a return value apply

3. Strategy pattern

The above-mentioned functional interface form actually separates the methods. The implementation method is still placed in a class. Even if you can call methods of other classes again through dependency injection in the FunctionInterfaceStrategy class, this pattern is already approaching the next method we are going to use, which is to use strategies. pattern to solve the if else

The form of the strategy pattern is suitable for situations where the implementation method is more complex and cleaner scenarios where the processing logic needs to be decoupled

1. First we need to create an interface class , used to specify the format of our subsequent implementation classes

public interface OrderStrategy {

    /**
     * 获取实现类标识
     * @return
     */
    Integer getType();

    /**
     * 逻辑处理
     * @param params
     * @return
     */
    Boolean handler(Object params);

}

2. Secondly, create an implementation class for each judgment condition

@Service
public class SendOrderStrategy implements OrderStrategy{

    @Override
    public Integer getType() {
        return 2;
    }

    @Override
    public Boolean handler(Object params) {
        // TODO 复杂的处理逻辑
        System.out.println("订单未发货");
        return true;
    }
}

@Service
public class SignOrderStrategy implements OrderStrategy{

    @Override
    public Integer getType() {
        return 3;
    }

    @Override
    public Boolean handler(Object params) {
        // TODO 复杂的处理逻辑
        System.out.println("订单未签收");
        return true;
    }
}

@Service
public class TakeOrderStrategy implements OrderStrategy{

    @Override
    public Integer getType() {
        return 1;
    }

    @Override
    public Boolean handler(Object params) {
        // TODO 复杂的处理逻辑
        System.out.println("订单未接单");
        return true;
    }
}

3. Create a strategy factory class to host the implementation class

@Component
@AllArgsConstructor
public class OrderStrategyFactory {

    private final List<OrderStrategy> orderStrategyList;

    private static Map<Integer,OrderStrategy> strategyMap = new HashMap<>();

    @PostConstruct
    private void init(){
        for (OrderStrategy orderStrategy : orderStrategyList) {
            strategyMap.put(orderStrategy.getType(),orderStrategy);
        }
    }

    /**
     * 执行方法
     * @param status
     * @param params
     * @return
     */
    public Boolean handler(Integer status,Object params){
        return strategyMap.get(status).handler(params);
    }

}

4. Method call

@RestController
@RequestMapping("ifelse")
@AllArgsConstructor
public class IfElseController {

    private final OrderStrategyFactory orderStrategyFactory;

    @GetMapping("strategy")
    public Boolean strategy(Integer status){
        return orderStrategyFactory.handler(status,"1");
    }

}

Summary:

Through the above code examples, you can actually find that functional interfaces and strategy patterns have similar approaches but the fundamental difference is Whether the implementation method needs to be extracted separately into an implementation class. The finer the extraction granularity, the stronger the decoupling.

Use the strategy mode. If you need to add if else conditions later, you only need to add the implementation class, which is more convenient for subsequent processing

Which one to use ultimately depends on the specific business situation

4. Guard statement

We often need to process various parameter nesting judgment logic before the method. If the conditions are not met, It is returned directly. In this case, it is more recommended to use the guard statement to process

Original statement

    public void before(Integer status) {
        if(status != null) {
            if(status != 0){
                if(status == 1){
                    System.out.println("订单未接单");
                }
            }
        }
    }

Guard statement

    public void greater(Integer status) {
        if(status == null){
            return;
        }
        if(status != 0){
            return;
        }
        if(status == 1){
            System.out.println("订单未接单");
        }
    }

The above is the detailed content of How to write if-else elegantly in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete