Using Java 8 Functional Interfaces to Replace if…else Statements
This article demonstrates how Java 8’s functional interfaces—such as Supplier, Consumer, Runnable, and Function—can replace repetitive if‑else statements for exception handling and branch logic, providing clear code examples, custom interfaces, and utility methods to simplify backend development.
During development, if...else... statements are often used for exception throwing and branch handling, which can clutter code. This guide shows how Java 8’s Function interface can eliminate such patterns.
Function Functional Interface
By annotating an interface with @FunctionalInterface and ensuring it contains only one abstract method, it becomes a functional interface. Common built‑in functional interfaces include Supplier (no arguments, returns a value), Consumer (accepts an argument, returns void), Runnable (no arguments, no return), and Function (accepts an argument and returns a value).
Function can be regarded as a transformation function.
Supplier (provider)
Supplier does not accept parameters and only returns data.
Consumer (consumer)
Consumer is the opposite of Supplier: it receives a parameter and returns nothing.
Runnable (no‑arg, no‑return)
Runnable has neither parameters nor a return value.
Function combines the behaviours of Supplier, Consumer and Runnable, acting as a conversion function.
Tip: Handling Exception‑Throwing if Statements
1. Define a functional interface
Create an interface that throws an exception; it has a parameter but no return value, making it a Consumer‑style functional interface.
/**
* Throw exception interface
*/
@FunctionalInterface
public interface ThrowExceptionFunction {
/**
* Throw an exception with the given message
* @param message exception message
*/
void throwMessage(String message);
}2. Write a utility method
In a utility class (e.g., VUtils ), add a method isTrue that returns a ThrowExceptionFunction . The function throws an exception when the supplied boolean is true.
/**
* If the parameter is true, throw an exception
*/
public static ThrowExceptionFunction isTrue(boolean b) {
return (errorMessage) -> {
if (b) {
throw new RuntimeException(errorMessage);
}
};
}3. Usage
Call the utility method and invoke throwMessage with the desired error text. When the argument is false, execution proceeds normally.
When the argument is true, an exception is thrown.
Handling if‑else Branches
1. Define a functional interface
Create BranchHandle with two Runnable parameters representing actions for true and false cases.
/**
* Branch handling interface
*/
@FunctionalInterface
public interface BranchHandle {
/**
* Execute the appropriate runnable based on the condition
* @param trueHandle action when condition is true
* @param falseHandle action when condition is false
*/
void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}2. Write a utility method
The method isTrueOrFalse returns a BranchHandle . It runs the appropriate runnable depending on the boolean argument.
/**
* Return a BranchHandle that executes trueHandle or falseHandle based on b
*/
public static BranchHandle isTrueOrFalse(boolean b) {
return (trueHandle, falseHandle) -> {
if (b) {
trueHandle.run();
} else {
falseHandle.run();
}
};
}3. Usage
When the parameter is true, trueHandle runs; otherwise falseHandle runs.
Present‑or‑Else Handling
1. Define a functional interface
PresentOrElseHandler accepts a Consumer for non‑null values and a Runnable for null values.
/**
* Handle present and empty values
*/
public interface PresentOrElseHandler
{
/**
* Execute action when value is present, otherwise run emptyAction
*/
void presentOrElseHandle(Consumer
action, Runnable emptyAction);
}2. Write a utility method
The method isBlankOrNoBlank returns a PresentOrElseHandler that checks a string and either runs the consumer with the string or runs the empty action.
/**
* Return a handler that processes a string based on whether it is blank
*/
public static PresentOrElseHandler
isBlankOrNoBlank(String str) {
return (consumer, runnable) -> {
if (str == null || str.length() == 0) {
runnable.run();
} else {
consumer.accept(str);
}
};
}3. Usage
Invoke presentOrElseHandle with a Consumer to process a non‑empty value and a Runnable for the empty case. The example prints the string when it is not empty.
Conclusion
The Function functional interface is a core feature of Java 8; leveraging it can greatly simplify code and improve readability in backend projects.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.