Use the Function interface in Java 8 to eliminate if Else (a very novel way of writing)

Source: Juejin cn/post/7011435192803917831

If is often used in the development process else... Judge, throw exceptions, branch processing and other operations. These if else... Flooding in the code seriously affects the beauty of the code. At this time, we can use the Function interface of Java 8 to eliminate if else....

if (...){
    throw new RuntimeException("An exception has occurred");
}

if (...){
    doSomething();
} else {
    doOther();
}

Function functional interface

The interface identified with the annotation @ FunctionalInterface and containing only one abstract method is a functional interface. Functional interfaces are mainly divided into Supplier supply Function, Consumer consumption Function, Runnable parameterless and non return Function and Function parameterless and return Function.

Function can be regarded as a conversion function

Supplier supply function

The form of Supplier is that it does not accept parameters and only returns data

Consumer consumption function

The consumer function is the opposite of the Supplier function. Consumer receives a parameter with no return value

Runnable parameterless and returnless function

The expression of Runnable is that there are no parameters and no return value

The expression of Function function is to receive a parameter and return a value. Supplier, Consumer and Runnable can be regarded as a special form of Function

Use tips

Handle if that throws an exception

1. Define function

Define a functional interface in the form of throwing exceptions. This interface has only parameters and no return value. It is a consumer interface

/**
 * Throw exception interface
 **/
@FunctionalInterface
public interface ThrowExceptionFunction {

    /**
     * Throw exception information
     *
     * @param message Abnormal information
     * @return void
     **/
    void throwMessage(String message);
}

2. Prepare judgment method

Create the tool class VUtils and create an isTure method. The return value of the method is the functional interface ThrowExceptionFunction just defined. The interface implementation logic of ThrowExceptionFunction is to throw an exception when parameter b is true

/**
 *  If the parameter is true, an exception is thrown
 *
 * @param b
 * @return com.example.demo.func.ThrowExceptionFunction
 **/
public static ThrowExceptionFunction isTure(boolean b){

    return (errorMessage) -> {
        if (b){
            throw new RuntimeException(errorMessage);
        }
    };
}

3. Usage

After calling the parameter parameters of the tool class, the throwMessage method of the functional interface is called to import the exception information. It is executed normally when the input and output parameters are false

An exception is thrown when the incoming and outgoing parameters are true

Handle if branch operations

1. Define functional interfaces

Create a functional interface named BranchHandle, and the parameters of the interface are two Runnable interfaces. These two Runnable interfaces respectively represent the operations to be performed when it is true or false

/**
 * Branch processing interface
 **/
@FunctionalInterface
public interface BranchHandle {

    /**
     * Branch operation
     *
     * @param trueHandle Operation to be performed when it is true
     * @param falseHandle Operation to be performed when it is false
     * @return void
     **/
    void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);

}

2. Prepare judgment method

Create a method named isTureOrFalse, and the return value of the method is the functional interface BranchHandle just defined.

/**
 * When the parameter is true or false, different operations are performed respectively
 *
 * @param b
 * @return com.example.demo.func.BranchHandle
 **/
public static BranchHandle isTureOrFalse(boolean b){

    return (trueHandle, falseHandle) -> {
        if (b){
            trueHandle.run();
        } else {
            falseHandle.run();
        }
    };
}

3. Usage

When the parameter is true, execute trueHandle

When the parameter is false, execute false handle

If there is a value, perform the consumption operation; otherwise, perform the null based operation

1. Define function

Create a functional interface named presentorsehandler, and the parameter of the interface is the Consumer interface. One is Runnable, which respectively represents the consumption operation when the value is not empty and other operations when the value is empty

/**
 * Null and non null branch processing
 */
public interface PresentOrElseHandler<T extends Object> {

    /**
     * The consumption operation is executed when the value is not empty
     * Perform other operations when the value is empty
     *
     * @param action Consumption operation executed when the value is not empty
     * @param emptyAction The action to be performed when the value is null
     * @return void
     **/
   void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);

}

2. Prepare judgment method

Create a method named isBlankOrNoBlank, and the return value of the method is the functional interface just defined - presentorsehandler.

/**
 * When the parameter is true or false, different operations are performed respectively
 *
 * @param b
 * @return com.example.demo.func.BranchHandle
 **/
public static PresentOrElseHandler<?> isBlankOrNoBlank(String str){

    return (consumer, runnable) -> {
        if (str == null || str.length() == 0){
            runnable.run();
        } else {
            consumer.accept(str);
        }
    };
}

3. Usage

After calling the parameter parameters of the tool class, the presentOrElseHandle method calling the functional interface brings in a Consumer and Runnable.

When the parameter is not empty, print the parameter

When the parameter is not empty

ending

Function function interface is a very important feature of java 8. Making good use of function function can greatly simplify the code.

Will you try this method in your code? Welcome to leave a message and say your opinion!

Recent hot article recommendations:

1.1000 + Java interview questions and answers (2022 latest version)

2.Hot! The Java collaboration is coming...

3.Spring Boot 2.x tutorial, too complete!

4.20w programmer red envelope cover, get it quickly...

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don't forget to like + forward!

Keywords: Java

Added by KirstyScott on Thu, 10 Feb 2022 20:36:02 +0200