How to avoid null pointer

How to avoid null pointer

The concept of Null Reference is sometimes referred to as “The Billion Dollar Mistake”.  In keeping with modern best practices, you want to eliminate null values from your code.

General rules about null and Option

We begin with the following general rules regarding the use of null values in Scala code:

  • Ban null from any of your code.
  • If you’re using a Java library that returns null, convert the result to a Scala .

One important rule when working with an Option:

  • Never call the get method on an Option. Always access Options using map or flatMap, the for expression, or pattern matching.

As you can infer by this statement, it’s important to note that Scala collection classes are created to work with Options. While using Option with constructs like for comprehensions and match expressions are nice, an enormous benefit of using Option is that they’re well supported by the methods of the collection classes.

Converting a null into an Option, or something else

The major place you’ll run into null values is in working with legacy Java code. There is no magic formula here, other than to capture the null value and return something else from your code. That may be an Option, a Null Object, an empty list, or whatever else is appropriate for the problem at hand.

For instance, the following getName method converts a result from a Java method that may be null and returns an Option[String] instead:

Following these guidelines leads to these benefits:

  • You’ll eliminate NullPointerExceptions.
  • Your code will be safer.
  • You won’t have to write if statements to check for null values.
  • Adding an Option[T] return type declaration to a method is a terrific way to indicate that something is happening in the method such that the caller may receive a None instead of a Some[T]. This is a much better approach than returning null from a method that is expected to return an object.
  • You’ll become more comfortable using Option, and as a result, you’ll be able to take advantage of how it’s used in the collection libraries and other frameworks.


Intro to stream APIs in Java

Intro to stream APIs in Java

Stream API was introduced in Java 8. It provided a declarative programming approach to iterate and perform operations over a collection. Until Java 7, for and for each were the only options available, which was an imperative programming approach. In this article I will introduce you to the Stream API and how it provides an abstraction over the common operations performed over a collection.

Before diving deep into the examples of operations performed over a collection using Stream API, let’s use an example to understand the Stream API itself.

In the above example, multiple operations are chained together to form something like a processing pipeline. This is what we refer as a stream pipeline. The stream pipeline made of the following three parts:

  1. Stream builder — In the above example, we have a collection of Person represented by people. The stream() method, that was added on the Collection interface in Java 8, is called upon people to build the stream. Common sources for stream apart from Collection are arrays (Arrays.stream()) and generator functions (Stream.iterate() and Stream.generate()).
  2. Intermediate operation(s) — Once a stream object is created, you can apply zero, one or more than one operations on the stream by chaining the operations, like in a builder pattern. All the methods that you see in the above example, filter and map, are methods on the Stream interface and they return the instance of Streamitself to enable chaining. As the operations return Stream itself, they are called intermediate operations.
  3. Terminal operation — Once all the computations are applied, you finish the pipeline by applying a mandatory terminal operator. The terminal operators are also methods on the Stream interface and return a resultant type that is not a Stream. In the example above the collect(Collectors.toList()) returns an instance of List. The resultant type may or may not be a Collection based on which terminal operation is used. It can be a primitive value or an instance of an object that is not a Collection.

Let’s now look at the basic operations that we can do using Stream. Though we will be learning about the operations applied individually on Stream, you can always mix and match them to derive different results.

Transforming

Transforming means converting the type of value that is stored in each element of a collection. Let’s say we want to derive a collection of names of people from the person collection. In such a case we have to use a transformation operation to transform the person to name.

In the example below, we use the map intermediate operator to transform People to a String holding the name of the person. Person::getName is a method reference and is equivalent to person -> person.getName() and is an instance of a Function.

Filtering

As the word suggests, filtering operations allow objects to flow through itself only if the object fulfills the conditions laid upon by a Predicate. The filter operator is composed with the Predicate before it is applied to the Stream.

Filtering can also be thought of as selecting few elements based on count. Stream API provides skip() and limit() operators for this purpose.

In the first example below, the person -> person.getAge() < 20 Predicate is used to build a collection containing only people below age of 20. In the second example below, 10 persons are selected after skipping first 2.

Searching

Again as the word suggests, searching on a collection means to search for an element or the existence of an element based on a criteria, which again is represented as a Predicate. Searching for an element may or may not return a value, hence you get an Optional. Searching for existence of an element will return a boolean.

In the examples below, searching for an element is done using findAny() and searching for existence is done using anyMatch().

Reordering

If you want to order the elements in a collection, you can use the sorted intermediate operator. It takes an instance of a Comparator interface. To create the instance I have used the comparing factory method on Comparator. If you are interested to know more around this, please checkout this link.

In the example below the resulting collection is sorted by age in descending order.

Unlike other operations we have seen till now, the sorted operation is stateful. It means that the operator will have to see all the elements in the stream before the result of sorting can be provided to further intermediate or terminal operator. Another example of such an operator is distinct.

Summary

Sometimes you want to derive information from a collection. As an example, deriving the sum of ages of all the people. In Stream API, this is achieved using terminal operatorsreduce and collect are the generic terminal operators provided for this purpose. There are high level operators also like sumcountsummaryStatistics, etc. that are built upon reduce and collect.