Java Reference
In-Depth Information
Chapter 4. Libraries
I've talked about how to write lambda expressions but so far haven't covered the other side
of the fence: how to use them. This lesson is important even if you're not writing a heavily
functional library like streams. Even the simplest application is still likely to have application
code that could benefit from code as data.
Another Java 8 change that has altered the way that we need to think about libraries is the in-
troduction of default methods and static methods on interfaces. This change means that
methods on interfaces can now have bodies and contain code.
I'll also fill in some gaps in this chapter, covering topics such as what happens when you
overload methods with lambda expressions and how to use primitives. These are important
things to be aware of when you're writing lambda-enabled code.
Using Lambda Expressions in Code
In Chapter 2 , I described how a lambda expression is given the type of a functional interface
and how this type is inferred. From the point of view of code calling the lambda expression,
you can treat it identically to calling a method on an interface.
Let's look at a concrete example framed in terms of logging frameworks. Several commonly
used Java logging frameworks, including slf4j and log4j , have methods that log output
only when their logging level is set to a certain level or higher. So, they will have a method
like void debug(String message) that will log message if the level is at debug .
Unfortunately, calculating the message to log frequently has a performance cost associated
with it. Consequently, you end up with a situation in which people start explicitly calling the
Boolean isDebugEnabled method in order to optimize this performance cost. A code sample
is shown in Example 4-1 . Even though a direct call to debug would have avoided logging the
text, it still would had to call the expensiveOperation method and also concatenate its out-
put to the message String , so the explicit if check still ends up being faster.
Example 4-1. A logger using isDebugEnabled to avoid performance overhead
Search WWH ::




Custom Search