Use "Function" to destroy if else

Posted by Gonwee on Tue, 04 Jan 2022 19:11:19 +0100

preface

If is often used in the development process else... Judge, throw exceptions, branch handling, etc. 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("Something's wrong");
} 

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

Function functional interface

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

Function can be regarded as a conversion function

Supplier supply function

The Supplier is expressed as not accepting parameters and only returning data

Consumer consumer 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 Function function takes a parameter and returns 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

java learning technology exchange q skirt: 603835449

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

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

 

 2. Write 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. Mode of use

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 incoming and outgoing parameters are false

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

 

Handle if branch operations

  • 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 Action to be taken when is true
     * @param falseHandle What to do when it is false
     * @return void
     **/
    void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);

}
  • Write 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 a value exists, perform the consumption operation; otherwise, perform the null based operation

  • 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 When the value is not empty, the consumption operation to be performed
     * @param emptyAction Action to be performed when the value is null
     * @return void    
     **/
   void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);
   
}

 

  • Write 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);
        }
    };
}
  • Mode of use
  • 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

    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.

More java learning materials can be added by clicking java learning group Get java learning materials free of charge, and answer questions free of charge by Java leaders who have developed Java for 10 years!

Topics: Java Back-end