

The Java SE 8 introduced the Optional type that acts as a "container object which may or may not contain a non-null value". It's a fairly error-prone approach and doesn't mitigate the fact that using null as a representative for absent things is risky.ĭoes Java offer any more sophisticated solutions to this problem? It does, at least in some situations. Throw new IllegalStateException("This system does not provide an audio device.") Ĭonstructs like these are part of any Java project and the approach works well unless you forget to add checks for certain variables. Applying this to the previous example brings us to the following solution: Device audio = new DeviceProvider().getAudioDevice() A common approach is to defensively check for null references and handle these cases in a way that makes more sense, such as providing default values or throwing more meaningful exceptions. We have to find strategies that help us avoiding unwanted bugs due to NPEs. Wouldn't it actually be nice if we were able to identify the method's returned Device type as nullable (or non-nullable respectively) firsthand? Null-Safety in Java Not knowing about the possibility of a returned null reference is going to cause an awful NullPointerException in the subsequent call to getName. Well documented methods will describe exactly that behavior, which still requires the developer to be very attentive. The method getAudioDevice returns an object of type Device but might return null in order to denote the absence of that device on particular systems. Have a look at the following code example: Device audio = new DeviceProvider().getAudioDevice() Although Java relies on strong static typing, it doesn't let you distinguish between reference types that can and cannot hold a null reference. The null reference is often used to indicate absent values, which isn't obvious to the programmer in many cases. This almost always happens unintentionally in consequence of a bug, which is based on unrecognized references to null. After that, the article demonstrates how Kotlin nullability features work and how they improve your code.Īs Java developers, we're very accustomed to NullPointerExceptions (NPE) that are thrown at the runtime of an application. In this article, we will review the problems that may be caused by null pointers and how to avoid them in Java. By s1m0nw1 2 Comments Null-Safe Programming - The Kotlin Wayĭisclaimer: This ktor article was originally published in the Dzone Java Guide 2018, which can be downloaded here.
