Handle Null like a pro using Optional 
Tags: java, backend, webdev, functional
Published: 2021-08-16 08:19:09

Many times we think that our code is perfect, works like a charm in the given scenarios and we proceed for deployment in production on a fine Friday. But when the code hits production due to unexpected data or due to some failure, when the code throws **NullPointerExcpetion**, the feeling comes like damn this weekend also ha... 

<img width="100%" style="width:100%" src="https://media.giphy.com/media/t9ctG5MZhyyU8/giphy.gif">

But Thank God, we have a rescuer to fight with **NPE(NullPointerException)** who came into the existence since Java 8 which is Optional class. 

<img width="100%" style="width:100%" src="https://media.giphy.com/media/mQeafe0Aev1PW/giphy.gif">

In this article let us find out how we can use Optional in day to day jobs.

To create Optional object we have two methods,

1. using of method
2. using ofNullable

Here are the examples

```java
Optional<String> optional = Optional.of("Chaitanya");
Optional<String> opNullable = Optional.ofNullable("Chaitanya");
```
If you think that there is a possibility of null coming because of the calling function then you can use **ofNullable**.

**of** method throws NPE if the value is null, so, if you're certain that you don't get a null value you can use **of** method. 

IMO, for simple operations like variable initialization or you've simple values and you want to pass them then you can use **of** method, if you're calling some external function for the result then you can use **ofNullable**.

Optional is something like a container that holds a value. To get things out of the container we need to open it, same way to get the value out of the **Optional**, we've **get** method. 

```java
Optional<String> optional = Optional.of("Chaitanya");
System.out.println(optional.get());
```

Think that you got a big container, you opened it and found nothing, then you feel disappointed right? To save from these kinds of bad feelings, we have **isPresent** method, usage is like this.

```java
Optional<String> nameOptional = getFirstName();
if(nameOptional.isPresent()) {
  System.out.println(nameOptional.get());
} else {
  System.out.println("No Name :( ");
}
```
If you want to handle in a functional style, here is the way

```java
nameOptional.ifPresent(value -> {
  System.out.println(value);
});
```
or using method references

```java
nameOptional.ifPresent(System.out::println);
```
Sometimes we don't want to do anything when an exception raises, without **Optional** one way is we return null in catch block, but from **Optional** we've one more method **empty()**, here is the usage:

```java
try {
  return Optional.ofNullable(getEmpName());
} catch (Exception ex) {
 return Optional.empty();
}
```

Sometimes we may need to manipulate the results of certain operations, in such cases, we've **map** and **flatMap** methods

```java
Optional<String> nameInUpperCaseOptional =                            
                       Optional.ofNullable(getEmpName())
                          .map(String::toUpperCase)
                          .get();
```
Here map returns one more Optional object with the transformed value. If you want to get direct value instead of Optional object, then you can use **flatMap** method.

```java
String nameInUpperCase = Optional.ofNullable(getEmpName())
                          .flatMap(String::toUpperCase);
```

If you want to return a default value when there is no value present, you can use **orElse** 

```java
String EMPTY = "";
String name = Optional.ofNullable(getEmpName())
                  .orElse(EMPTY);
```

If you want to perform some action when there is no value present, you can use **orElseGet**

```java
String name = Optional.ofNullable(getEmpName())
                  .orElseGet(_ -> System.out.println("There is no Value :( "));
```

If you want to throw an exception when there is no value present then we've **orElseThrow**

```java
String name = Optional.ofNullable(getEmpName())
                  .orElseThrow(Exception::new);
```

In Java 11, There are some more enhancements in Optional class like **ifPresentElse**, **or**, **stream**, here is the link to documentation for further details. [Java 11#Optional] (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html)

That is it for this article :) If you use **Optional** properly you can pretty much avoid **NPE** and can avoid stressful weekends too.

<img width="100%" style="width:100%" src="https://media.giphy.com/media/kiBcwEXegBTACmVOnE/giphy.gif">

Thanks for spending time. I appreciate your feedback.