How to Replace if…else with Java 8 Functional Interfaces for Cleaner Code

This article explains how Java 8's functional interfaces—Supplier, Consumer, Runnable, and Function—can replace verbose if…else statements for exception handling, branching, and value checks, providing concise, readable code with practical examples and utility methods.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
How to Replace if…else with Java 8 Functional Interfaces for Cleaner Code

During development, developers often rely on if...else... for exception throwing and branch handling, which makes the code look cluttered. Java 8's Function interface can be used to eliminate these repetitive if...else... constructs.

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

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

Function Functional Interface

By annotating an interface with @FunctionalInterface and ensuring it contains only one abstract method, it becomes a functional interface. The main categories are: Supplier – a no‑argument function that returns a value. Consumer – a function that accepts a single argument and returns nothing. Runnable – a function with no arguments and no return value. Function – a function that accepts an argument and returns a result.

Function can be regarded as a conversion function.

Supplier – Supply Function

Supplier

does not accept parameters and only returns data.

Consumer – Consumption Function

Consumer

is the opposite of Supplier; it receives one argument and has no return value.

Runnable – No‑Argument No‑Return Function

Runnable

represents a function with neither parameters nor a return value.

Function – Parameter‑Return Function

Function

accepts one argument and returns a value. It can be seen as a specialized form of Supplier, Consumer, and Runnable.

Practical Tips

Handling Exception‑Throwing if

Define a functional interface that throws an exception; it is a Consumer -style interface.

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

Create a utility method isTure that returns the above interface. When the boolean parameter b is true, the method throws the provided exception.

/**
 * 如果参数为true抛出异常
 * @param b
 * @return ThrowExceptionFunction
 */
public static ThrowExceptionFunction isTure(boolean b) {
    return (errorMessage) -> {
        if (b) {
            throw new RuntimeException(errorMessage);
        }
    };
}

Usage: call isTure(false) to get a function that does nothing, or isTure(true) to get a function that throws the supplied message.

Handling if Branch Operations

Define a functional interface BranchHandle that receives two Runnable instances—one for the true case and one for the false case.

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

Create a method isTureOrFalse that returns a BranchHandle . It executes the appropriate Runnable based on the boolean argument.

/**
 * 参数为true或false时,分别进行不同的操作
 * @param b
 * @return BranchHandle
 */
public static BranchHandle isTureOrFalse(boolean b) {
    return (trueHandle, falseHandle) -> {
        if (b) {
            trueHandle.run();
        } else {
            falseHandle.run();
        }
    };
}

Usage: when the argument is true , the trueHandle runs; otherwise the falseHandle runs.

Handling Value‑Present or Empty Cases

Define a generic functional interface PresentOrElseHandler that takes a Consumer for non‑null values and a Runnable for null/empty values.

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

Create a method isBlankOrNoBlank that returns this interface. It runs the Consumer when the string is non‑empty, otherwise runs the Runnable .

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

Usage: pass a Consumer that prints the value and a Runnable for the empty case.

Conclusion

The Function functional interface is a crucial feature of Java 8; leveraging it can dramatically simplify code by removing repetitive if...else structures.

clean codebackend-developmentfunctional-interfacejava-8
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

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.