How to Replace Cluttered if…else… with Java 8 Functional Interfaces
This article explains how Java 8's @FunctionalInterface and its built‑in functional types (Supplier, Consumer, Runnable, Function) can be used to eliminate repetitive if…else… statements, with concrete code examples for exception handling, branch processing, and optional value handling.
In development, the overuse of if...else... for exception throwing or branching makes code hard to read; Java 8’s Function functional interface can eliminate such patterns.
if (...) {
throw new RuntimeException("出现异常了");
}
if (...) {
doSomething();
} else {
doOther();
}Function Functional Interface
Using the @FunctionalInterface annotation, an interface that contains exactly one abstract method becomes a functional interface. The main built‑in functional interfaces are Supplier (no arguments, returns a value), Consumer (accepts one argument, returns nothing), Runnable (no arguments, no return), and Function (accepts one argument, returns a value).
Function can be regarded as a conversion function.
Supplier (Supply‑type function)
Supplier takes no parameters and returns data.
Consumer (Consume‑type function)
Consumer is the opposite of Supplier: it accepts one argument and returns nothing.
Runnable (No‑arg, no‑return function)
Runnable has neither parameters nor a return value.
Function (Conversion function)
Function receives one argument and returns a value. Supplier, Consumer and Runnable can be seen as special cases of Function.
Practical Tips
Handling Exceptions with if
1. Define a 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 method that returns the interface
/**
* Returns a ThrowExceptionFunction that throws when the boolean is true
*/
public static ThrowExceptionFunction isTrue(boolean b) {
return (errorMessage) -> {
if (b) {
throw new RuntimeException(errorMessage);
}
};
}3. Usage
Call the utility method and invoke throwMessage with an error string; the exception is thrown only when the argument is true.
Handling Branches with if
1. Define a functional interface
/**
* Branch handling interface
*/
@FunctionalInterface
public interface BranchHandle {
/**
* Execute different actions for true/false
*/
void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}2. Write a method that returns the interface
/**
* Returns a BranchHandle that runs the appropriate Runnable based on the boolean
*/
public static BranchHandle isTrueOrFalse(boolean b) {
return (trueHandle, falseHandle) -> {
if (b) {
trueHandle.run();
} else {
falseHandle.run();
}
};
}3. Usage
When the parameter is true, the trueHandle runs; otherwise falseHandle runs.
Handling Optional Values
1. Define a functional interface
/**
* Handle present or empty values
*/
public interface PresentOrElseHandler<T> {
/**
* Execute a Consumer when the value is present, otherwise run a Runnable
*/
void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);
}2. Write a method that returns the interface
/**
* Returns a handler that runs a Consumer if the string is non‑empty, otherwise a Runnable
*/
public static PresentOrElseHandler<?> isBlankOrNoBlank(String str) {
return (consumer, runnable) -> {
if (str == null || str.length() == 0) {
runnable.run();
} else {
consumer.accept(str);
}
};
}3. Usage
Pass a Consumer and a Runnable to presentOrElseHandle; the appropriate action runs based on whether the value is null/empty.
Conclusion
The Function functional interface is a core feature of Java 8; leveraging it can dramatically simplify code by removing repetitive if…else… constructs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
