Today I am going to show you what it is Optional type in Java and how to use it correctly. Java 8 provides us with a new Optional class, which allows for better protection against null pointer exceptions.
Optional type - variations and usage
Empty Optional object
public staticOptional empty() {
@SuppressWarnings("unchecked")
Optionalt = (Optional ) EMPTY;
return t;
}
Way to use:
@Test
public void createsEmptyOptional()
Optionalempty = Optional.empty();
assertThat(empty.isPresent(), is(false));
}
So we created empty optional object and in next step we use isPresent() to check if insde optional object is any value.
Optional of some object
public staticOptional of(T value) {
return new Optional(value);
}
Way to use:
@Test
public void createsOptionalUsingOf() {
String toTest = "to test";
Optionalempty = Optional.of(toTest);
assertThat(empty.isPresent(), is(true));
}
So we created non empty optional object and in next step we use isPresent() to check if insde optional object is any value present.
Null Pointer Exception with optional type
But what happens when we pass null to the Optional object?
@Test (expected = NullPointerException.class)
public void createsOptionalUsingOf() {
String toTest = null;
Optionalempty = Optional.of(toTest);
assertThat(empty.isPresent(), is(false));
}
We should expect null pointer exception.
Optional ofNullable to the rescue
public staticOptional ofNullable(T value) {
return value == null ? empty() : of(value);
}
Way to use
@Test
public void createsOptionalUsingOfNullable() {
String toTest = null;
Optionalempty = Optional.ofNullable(toTest);
assertThat(empty.isPresent(), is(false));
}
So when we use ofNullable to create optional object we do not get null pointer exception when we pass null parameter. Insted we get an empty optional object.
From Java 11 we can use both isEmpty() and isPresent() methods to check if optional object is empty.
Optional type summary
We need to remember not to over-use Optional type and not to over-engineer. For example it makes perfect sense to use it as a return type, especially in the methods that finds something.We should avoid using it as a class members or as arguments to methods or constructors. Sometimes there are exceptions when we can justify such usage.
That's it as a short introduction to it.
This post first appeared on IT Code Hub - Java, Mobile Apps, Linux And More, please read the originial post: here