Java Reference
In-Depth Information
Chapter 7
Lambdas and Legacy Code
At this point in this topic, you have seen all the wonderful things that lambdas can do for your codebase. But
what about the huge pile of legacy code that is out there? There is a lot of code to be merged into this new
reality, and a lot of Java developers are commited to projects that have to drag forward those balls of mud.
How can lambdas make their life easier?
Furthermore, the new Java 8 APIs are very impressive, but there are many APIs in the Java SDK that have
not yet been updated for the brave new lambda world. How do you take advantage of lambdas with APIs that
are not at all intended to support it?
The good news is that the Java language's developers have been long concerned about this issue. Java
is by its nature a conservative language, so the language developers could not break any of the existing Java
code with radical language changes. The language developers could, however, add in new features and
provide new powers and new APIs. Most important, they provided key functionality to bridge legacy code
into our new world. That functionality, combined with a few key practices, means there is only a minor bit of
code necessary to gain all the power of lambdas, even from code that has no idea about them.
Resources and Exceptions
The most awkward legacy pattern in Java is the “try-with-resource” pattern. This is where a stateful
object - usually either an I/O object or a pool - needs to be put from an initial condition into an operational
condition before you can use it, and then that stateful object also needs to be cleaned up when your user
operation is completed on it. This pattern is widely adopted and conceptually works quite nicely with
object-oriented programming. However, the implementation of this pattern has never worked well in Java,
and the language has struggled with ways to improve it since the start.
Initially, this pattern required you to declare a variable outside of a scope, then enter into a try/catch
block. It was 14 additional lines of code required for each resource, which looked something like this:
InputStream in = null;
try {
in = acquireInputStream();
// Do something with “in”
} finally {
if (in != null) {
try {
in.close();
} catch (IOException closeException) {
// What now?
}
in = null;
}
}
 
Search WWH ::




Custom Search