Java Reference
In-Depth Information
deferred execution and execute around . In addition, in the next section we show how many
object-oriented design patterns such as strategy and template method can be rewritten more
concisely using lambda expressions.
Conditionaldeferred execution
It's common to see control-flow statements mangled inside business logic code. Typical
scenarios include security checks and logging. For example, consider the following code that
uses the built-in Java Logger class:
if (logger.isLoggable(Log.FINER)){
logger.finer("Problem: " + generateDiagnostic());
}
What's wrong with it? A couple of things:
The state of the logger (what level it supports) is exposed in the client code through the method
isLoggable .
Why should you have to query the state of the logger object every time before you can log a message?
It just clutters your code.
A better alternative is to make use of the log method, which internally checks to see if the logger
object is set to the right level before logging the message:
logger.log(Level.FINER, "Problem: " + generateDiagnostic());
This is a better approach because your code isn't cluttered with if checks, and the state of the
logger is no longer exposed. Unfortunately, there's still an issue with this code. The logging
message is always evaluated, even if the logger isn't enabled for the message level passed as
argument.
This is where lambda expressions can help. What you need is a way to defer the construction of
the message so it can be generated only under a given condition (here, when the logger level is
set to FINER). It turns out that the Java 8 API designers knew about this problem and
introduced an overloaded alternative to log that takes a Supplier as argument. This alternative
log method has the following signature:
public void log(Level level, Supplier<String> msgSupplier)
You can now call it as follows:
 
Search WWH ::




Custom Search