Java Reference
In-Depth Information
There are a few key heuristics that can help you out when identifying an appropriate place to
lambdify your application or library code. Each of these can be considered a localized antip-
attern or code smell that you're fixing through point lambdification.
In, Out, In, Out, Shake It All About
In Example 7-1 , I've repeated our example code from Chapter 4 about logging statements.
You'll see that it's pulling out the Boolean value from isDebugEnabled only to check it and
then call a method on the Logger . If you find that your code is repeatedly querying and oper-
ating on an object only to push a value back into that object at the end, then that code be-
longs in the class of the object that you're modifying.
Example 7-1. A logger using isDebugEnabled to avoid performance overhead
Logger logger = new
new Logger ();
iif ( logger . isDebugEnabled ()) {
logger . debug ( "Look at this: " + expensiveOperation ());
}
Logging is a good example of where this has historically been difficult to achieve, because in
different locations you're trying to provide different behavior. In this case, the behavior is
building up a message string that will differ depending upon where in your program you're
logging and what information you're trying to log.
This antipattern can be easily solved by passing in code as data. Instead of querying an object
and then setting a value on it, you can pass in a lambda expression that represents the relev-
ant behavior by computing a value. I've also repeated the code solution in Example 7-2 , as a
reminder. The lambda expression gets called if we're at a debug level and the logic for
checking this call remains inside of the Logger itself.
Example 7-2. Using lambda expressions to simplify logging code
Logger logger = new
new Logger ();
logger . debug (() -> "Look at this: " + expensiveOperation ());
Logging is also a demonstration of using lambda expressions to do better object-oriented
programming (OOP). A key OOP concept is to encapsulate local state, such as the level of
the logger. This isn't normally encapsulated very well, as isDebugEnabled exposes its state.
If you use the lambda-based approach, then the code outside of the logger doesn't need to
check the level at all.
Search WWH ::




Custom Search