This is the second and final part of a two post series on some of the new features and enhancements in Java 8. In the first post, we covered lambda expressions, method references, default methods and static methods in interfaces, and looked briefly at how we could debug lambda expressions. Since I did all the necessary Java 8 introductions in the first part, let’s just get on with what you came here for: A second dip into what’s new in Java 8.
To prevent the code samples from getting wider than the page, I’ve taken the liberty to omit the “final” keyword where it would be natural to use it. Also, most of the code below won’t compile as-is, since I’ve omitted the class declarations – but all the code examples used are available in compilable and runnable versions on GitHub, so why don’t you go ahead; clone that repo and knock yourself out.
One of the biggest pitfalls in Java is the dreaded NullPointerException, or NPE for short. An NPE is an unchecked exception that will only be thrown at runtime and when the NPE bomb goes off, bad things are likely to happen. Preventing an NPE in your code really isn’t that hard, it’s just tedious and creates code that should be unnecessary.
Let’s say you use a badly documented third party API. The API contains a method that you know returns a List of Integers because it says so in the method signature and you use the method in your code like this:
List<Integer> integers = ThirdPartyAPI.getIntegers();
The problem with this code is that you don’t know what the third party implementing the API has decided to return if there are no Integer objects to return. Will the method return an empty list? Or will it return “null”? If the former is the case, you’re home free, but if the latter is the case, line #2 will cause an NPE to be thrown. It might be that you know that the method returns an empty List if there are no Integer objects to return – you could have written a unit test that somehow proves it or even reverse engineered the third party code – so you feel that the above code is safe. But what happens if the API developer for some reason decides to change the implementation so that “null” is returned instead of an empty list? Then you’ve suddenly got a major “whoopsie” in your code. It’s not your fault, per se, but I doubt that your client cares much about whose fault it is.
In our case, we’re lucky enough to have access to the source code for the third party API: