The second-best feature of Java 8

Joshua Hendrickson posted September 21, 2015

After far too longJava 8 finally adds support for real, actual lambda expressions in all of the places you hoped it would. I know of no one who would dispute that the best new feature in Java 8 is support for this basic construct that will simplify code and improve readability. However, you may not be aware that Java 8 includes more new features than just lambda support. So which feature of Java 8 ranks second best? I claim that you will grow to love java.util.Map#getOrDefault() almost as much as you love lambdas.

Why Programmers Love Python, Part 11515

Of any programming language I’ve learned in the last several years, Python has carved out a special place in my heart. The language offers easy syntax, object orientation, functional support, platform interoperability, and many other neat features. Consider also its fantastic librarypackage repositoryopen-source development, and superb documentation. Today, Django offers a web development framework gives you all the power of Python combined with rapid development of MVC websites. Did I mention most of the popular Integrated Development Environments provide first-class support for Python?

All that stuff is fantastic, but when I first encountered this little API for Python’s dict class, it changed my life:


Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

This means that instead of writing stuff like:

You can instead write this (assuming you have defined EMPTY_MEMBER suitably):

Now imagine that substituted for every case where you have code similar to the first sample. I bet you can recognize how much get() can simplify your code. Indeed, if you see any Python code that tries to handle KeyError, I’m willing to bet you have the opportunity to improve that code using get().

dict comes to java.util.Map

In Java, on the other hand, no such API existed. To my happy surprise, I discovered the new getOrDefault() method while reviewing some code that had to make use of a pattern like the following:

You can write this much more concisely using getOrDefault():

While it is true that the ternary operator ( ?: ) could be used in this case, it is denser than the method call above. If you don’t like to use ?:, then this new API can save you several lines each time. In larger classes, you could be talking removal of dozens of lines of boilerplate. Since one of the most reliable measures of the quality of code is its length, taking easy steps like this to reduce number of lines and statements in a class will improve quality for little cost.


Leave a Reply

Your email address will not be published. Required fields are marked *