Table of Contents
1. switch
2. Functional interface
3. Strategy pattern
4. Guard statement
Home Java javaTutorial How to write if-else elegantly in Java

How to write if-else elegantly in Java

Apr 29, 2023 pm 10:04 PM
java if-else

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("订单已签收");
        }
    }
Copy after login

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("订单已签收");
        }
    }
Copy after login

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;
    }

}
Copy after login

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);
Copy after login

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 nameDescriptionCalling method
SupplierNo parameters, There is a return valueget
ConsumerThere are parameters, no return valueaccept
RunnableNo parameters, no return valuerun
FunctionWith parameters, there is a return valueapply

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);

}
Copy after login

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;
    }
}
Copy after login

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);
    }

}
Copy after login

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");
    }

}
Copy after login

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("订单未接单");
                }
            }
        }
    }
Copy after login

Guard statement

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles