Java table driven (map) function instead of if...else code

Map + functional interface method replaces many if...else judgments.

What is table-driven approach?

Is a programming pattern that looks up information from tables without using logic statements (if and case). In fact, all things that can be selected by logical statements can be selected by looking up tables. For simple cases, it is easier and more straightforward to use logical statements, but as the logic chain becomes more and more complex, the look-up table method becomes more and more attractive.

General rules of use

When appropriate, the table-driven approach can generate code that is simpler, easier to modify, and more efficient than complex logic code.

Table-Driven Function (Table-Driven Function) is a common programming technique, which can convert a series of conditional judgment statements into a table-based lookup operation, thereby improving the readability and maintainability of the code. In JAVA, we can use different data structures to implement table driven functions. In addition to arrays, you can also use Maps, Lists, or other data structures. Choosing different data structures depends on specific application scenarios and requirements.

The main advantage of table-driven functions is that it can make the code more concise, easier to understand and maintain. Using table-driven functions, a large number of conditional judgment statements can be converted into a simple table, thereby reducing the amount of code, reducing the risk of errors, and making the code easier to expand and modify. It should be noted that using table-driven functions is not always better than using conditional judgment statements, it depends on the specific situation. In some cases, it may be more intuitive and simpler to use conditional judgment statements. Therefore, we need to choose the most suitable programming technique according to the actual situation.

Implement functions with Function

Function can only have one input parameter and one output parameter

The get method will throw an exception if it cannot be retrieved

getOrDefault will return the default value if it cannot be obtained

apply is equivalent to executing the value function in map

If you need two input parameters and one output parameter, you can use BiFunction

If you need two input parameters and no return parameters, that is, the method return type is void, you can use BiConsumer

There are also many functions with different numbers of input and output parameter types:

The packaging class table corresponding to the basic type is as follows:

basic type

reference type

boolean

Boolean

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

char

Character

Simple sample code:

import java.util.HashMap;
import java.util.function.Function;

public class Demo {
    public static void main(String[] args) {
        String aResult = dataMappings.getOrDefault("0", defaultMapping).apply("a-result");
        System.out.println(aResult);
        String bResult = dataMappings.get("1").apply("b-result");
        System.out.println(bResult);
        String cResult = dataMappings.getOrDefault("3", defaultMapping).apply("c-result");
        System.out.println(cResult);
        String defaultResult = dataMappings.getOrDefault("100", defaultMapping).apply("default-result");
        System.out.println(defaultResult);
    }

    static HashMap<String, Function<String, String>> dataMappings = new HashMap<String, Function<String, String>>() {
        {
            put("0", (String param) -> {
                return param;
            });
            put("1", (String param) -> {
                return param;
            });
            put("2", (String param) -> {
                return param;
            });
            put("3", (String param) -> {
                return deal(param);
            });
            put("4", (String param) -> {
                return deal(param);
            });
        }
    };

    static Function<String, String> defaultMapping = new Function<String, String>() {
        @Override
        public String apply(String s) {
            return "default";
        }
    };

    static String deal(String param) {
        return "after deal:" + param;
    }
}

operation result:

a-result

b-result

after deal:c-result

default

Guess you like

Origin blog.csdn.net/xijinno1/article/details/132137672