Java Reference
In-Depth Information
logger.log(Level.FINER, () -> "Problem: " + generateDiagnostic());
The log method will internally execute the lambda passed as argument only if the logger is of the
right level. The internal implementation of the log method is along the lines of this:
What's the takeaway from the story? If you see yourself querying the state of an object many
times in client code (for example, the state of the logger), only to call some method on this object
with arguments (for example, log a message), then consider introducing a new method that calls
that method (passed as a lambda or method reference) only after internally checking the state of
the object. Your code will be more readable (less clutter) and better encapsulated (the state of
the object isn't exposed in client code)!
Execute around
In chapter 3 we discussed another pattern that you can adopt: execute around. If you find
yourself surrounding different code with the same preparation and cleanup phases, you can
often pull that code into a lambda. The benefit is that you reuse the logic dealing with the
preparation and cleanup phases, thus reducing code duplication.
To refresh, here's the code you saw in chapter 3 . It reuses the same logic to open and close a file
but can be parameterized with different lambdas to process the file:
 
Search WWH ::




Custom Search