search
HomeJavajavaTutorialHow to write if-else elegantly in Java

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:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How can I use Java's RMI (Remote Method Invocation) for distributed computing?How can I use Java's RMI (Remote Method Invocation) for distributed computing?Mar 11, 2025 pm 05:53 PM

This article explains Java's Remote Method Invocation (RMI) for building distributed applications. It details interface definition, implementation, registry setup, and client-side invocation, addressing challenges like network issues and security.

How do I use Java's sockets API for network communication?How do I use Java's sockets API for network communication?Mar 11, 2025 pm 05:53 PM

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i

How can I create custom networking protocols in Java?How can I create custom networking protocols in Java?Mar 11, 2025 pm 05:52 PM

This article details creating custom Java networking protocols. It covers protocol definition (data structure, framing, error handling, versioning), implementation (using sockets), data serialization, and best practices (efficiency, security, mainta

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)