Replace Repetitive if…else… with Java 8 Functional Interfaces

This article explains how Java 8 functional interfaces such as Function, Supplier, Consumer, and Runnable can be used to eliminate cluttered if‑else statements, showing practical examples for exception handling, branch processing, and null‑value handling with concise lambda‑based code.

Programmer DD
Programmer DD
Programmer DD
Replace Repetitive if…else… with Java 8 Functional Interfaces

During development, if...else... statements are often used for exception throwing and branching, which can clutter code. Java 8’s Function interface can replace these repetitive if...else... constructs.

if (...) {
    throw new RuntimeException("出现异常了");
}
if (...) {
    doSomething();
} else {
    doOther();
}

Function Functional Interface

Mark an interface with @FunctionalInterface to indicate it contains a single abstract method. Functional interfaces include Supplier (no arguments, returns a value), Consumer (accepts an argument, no return), Runnable (no arguments, no return), and Function (accepts an argument and returns a value).

Function can be seen as a transformation function.

Supplier

Supplier has no parameters and returns data.

Consumer

Consumer is the opposite of Supplier: it accepts a parameter and returns nothing.

Runnable

Runnable has neither parameters nor return value.

Function

Function receives a parameter and returns a value. Supplier, Consumer, and Runnable can be considered special cases of Function.

Tips

Handling Exceptions with if

1. Define a functional interface

/**
 * 抛异常接口
 */
@FunctionalInterface
public interface ThrowExceptionFunction {
    /**
     * 抛出异常信息
     * @param message 异常信息
     * @return void
     */
    void throwMessage(String message);
}

2. Write a method that returns the interface

public static ThrowExceptionFunction isTrue(boolean b) {
    return (errorMessage) -> {
        if (b) {
            throw new RuntimeException(errorMessage);
        }
    };
}

3. Use it

Call the utility method and invoke throwMessage with an error message; when the argument is false the code runs normally.

Processing Branches with if

1. Define a functional interface

/**
 * 分支处理接口
 */
@FunctionalInterface
public interface BranchHandle {
    /**
     * 分支操作
     * @param trueHandle  为true时要进行的操作
     * @param falseHandle 为false时要进行的操作
     * @return void
     */
    void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}

2. Write a method that returns the interface

public static BranchHandle isTrueOrFalse(boolean b) {
    return (trueHandle, falseHandle) -> {
        if (b) {
            trueHandle.run();
        } else {
            falseHandle.run();
        }
    };
}

3. Use it

When the parameter is true, the trueHandle runs; otherwise the falseHandle runs.

Handling Optional Values

1. Define a functional interface

/**
 * 空值与非空值分支处理
 */
public interface PresentOrElseHandler<T extends Object> {
    /**
     * 值不为空时执行消费操作,值为空时执行其他的操作
     * @param action      值不为空时执行的消费操作
     * @param emptyAction 值为空时执行的操作
     */
    void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);
}

2. Write a method that returns the interface

public static PresentOrElseHandler<?> isBlankOrNoBlank(String str) {
    return (consumer, runnable) -> {
        if (str == null || str.length() == 0) {
            runnable.run();
        } else {
            consumer.accept(str);
        }
    };
}

3. Use it

Call the utility method and invoke presentOrElseHandle with a Consumer and a Runnable. When the string is non‑empty, the consumer prints the value; otherwise the runnable runs.

Conclusion

Function functional interfaces are a powerful feature of Java 8; using them can greatly simplify code. Will you try this approach in your projects?

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaLambdaFunctional InterfaceJava 8if-else
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.