Sunday, July 29, 2018

Features to Avoid Null Reference Exceptions in Java and Swift

Have you recently faced a NullPointerException in your code? If not, then you must be a careful writer. One of the most common exception types in Java applications are  NullPointerExceptions. As long as the language allows us to assign null values to any object, it will always be easy to write a small piece of code, which, at some point, will cause a NullPointerException and crash the entire system. The java.util.Optional<T> class was introduced in Java 8 to alleviate this problem. Indeed, the Optional's API turns out to be quite powerful. There are plenty of cases where Optionals fit well. However, they are not designed to completely solve the problem with NullPointerExceptions. Additionally, Optionals themselves are very easy to be misused. A good indicator for that is the number of articles that are often being published on how Optionals should or should not be used.
In contrast to Java, the type systems of other languages, like Kotlin, Swift, Groovy and more, are able to distinguish between variables that are allowed to point to null values and those that are not. In other words, they do not allow a null value to be assigned to a variable unless it is explicitly declared as nullable. In this article, we will give an overview of some features of different programming languages that reduce or avoid the necessity of working with null values.

Java Optionals

With java.util.Optional<T> introduced in Java 1.8, the need for null references is significantly reduced. Nevertheless, some care is needed when creating an instance of an Optional or when using it. For instance, the Optional.get method will throw a NoSuchElementException if the value is not present, or the Optional.of method will throw a NullPointerException if the provided value is null. Therefore, both of these methods are as risky as directly de-referencing potential null values. One benefit we get from an Optional is that it provides a set of higher order functions, which can be chained without worrying whether the value is present or not.



from DZone.com Feed https://ift.tt/2NSnWTb

No comments:

Post a Comment