Optional Class in Java 8: Making Your Code More Clear and Concise .
Why Optional Class ?
The Optional class in Java 8 is a container object which is used to contain a value that might or might not be present. It was introduced as a way to help reduce the number of NullPointerExceptions that occur in Java code. It is a part of the java.util package and was added to Java as part of Java 8.
Optional is a container that either contains a non-null value or nothing(empty Optional ). The Optional class is an implementation of the Null Object pattern, which is a design pattern that was designed to reduce the number of null checks in code. With Optional, you can write cleaner and more concise code that is easier to maintain.
One of the key benefits of using Optional is that it forces you to handle the case where the value is absent. This means that you are less likely to miss important checks in your code and reduces the risk of NullPointerException. If a value is not present, you can either provide a default value or throw an exception.
Example (Problem with null):
public class Main {
public static void main(String[] args) {
Student Student = getStudentWithName("hamza");
System.out.println(Student.getName());
}
public static Student getStudentWithName(String name ){
// lets suppose that our database contain only 2 students ahmed and hamza .
if (name.equals("hamza") || name.equals("ahmed")) {
return new Student(name , 22 , "Morocco");
} else {
return null ;
}
}
}
It’s obvious that getStudentWithName() can return a null if there is no student with the given name => NullPointerException will occur when we call the getName() method (student = null ).
To handle this case, we should implement some form of conditional logic based on the result returned by the method.
public class Main {
public static void main(String[] args) {
Student Student = getStudentWithName("hamza");
if(student != null){
System.out.println(Student.getName());
}else {
System.out.println("no Student with the given name ");
}
}
public static Student getStudentWithName(String name ){
// lets suppose that our database contain only 2 students ahmed and hamza .
if (name.equals("hamza") || name.equals("ahmed")) {
return new Student(name , 22 , "Morocco");
} else {
return null ;
}
}
}
To avoid NullPointerException problems, let’s examine what the Optional API offers.
Optional class methods
Optional.ofNullable(T) , Optional.of(T) , Optional.empty() .
To use the Optional class, simply wrap your object in an Optional object like this: Optional<T> optional = Optional.ofNullable(T). You can then use the various methods provided by Optional to handle the cases where the value is present or not. For example, the isPresent() method returns true if the value is present, and false if it is not.
This method behave like the ofNullable() function it will return an Optional for the given value the only difference is that the of() method does not allow to construct an Optional object around a null value .
领英推荐
Optional<Student> student = Optional.of(null);
this line will throw a NullPointerException .
this method will simply generate an empty Optional (no value ).
Optional<T> empty = Optional.empty();
The Optional class provides several methods that can be used to interact with the value that is stored inside the Optional. For example, the isPresent() method can be used to check if a value is present or not. If a value is present, you can use the get() method to retrieve it.
now let’s try to refactor our exemple using Optional API .
public class Main {
public static void main(String[] args) {
Optional<Student> student = Optional.ofNullable(getStudentWithName("hamza"));
if (student.isPresent()) {
System.out.println(student.get().getName());
} else {
System.out.println("Student is not present");
}
}
public static Student getStudentWithName(String name ){
// lets suppose that our database contain only 2 students ahmed and hamza .
if (name.equals("hamza") || name.equals("ahmed")) {
return new Student(name , 22 , "Morocco");
} else {
return null ;
}
}
}
Of course, there are still if-else blocks in this logic, but let’s examine other useful methods provided by the Optional API to reduce its use.Of course, there are still if-else blocks in this logic, but let’s examine other useful methods provided by the Optional API to reduce its use.
Make your code more concise using orElse() , orElseThrow() .
orElse is a method in the Java Optional class that is used to return the value wrapped in the Optional, if it is present, or a default value if it is not. It takes a default value as an argument and returns it if the Optional is empty.
public class Main {
public static void main(String[] args) {
Student student = Optional.ofNullable(getStudentWithName("hamza")).orElse(new Student("no one", 0, "Unknown"));
System.out.println(student.getName());
}
public static Student getStudentWithName(String name ){
// lets suppose that our database contain only 2 students ahmed and hamza .
if (name.equals("hamza") || name.equals("ahmed")) {
return new Student(name , 22 , "Morocco");
} else {
return null ;
}
}
}
orElseThrow is a method in the Java Optional class that is used to throw an exception if the Optional is empty. Unlike orElse, which returns a default value, orElseThrow allows you to throw a custom exception.
Here’s an example:
public class Main {
public static void main(String[] args) throws StudentNotFoundException {
Student student = Optional.ofNullable(getStudentWithName("fs")).orElseThrow(()-> new StudentNotFoundException("the Student is not Present "));
System.out.println(student.getName());
}
public static Student getStudentWithName(String name ){
// lets suppose that our database contain only 2 students ahmed and hamza .
if (name.equals("hamza") || name.equals("ahmed")) {
return new Student(name , 22 , "Morocco");
} else {
return null ;
}
}
}
In conclusion, the Optional class in Java 8 is a useful tool for reducing the number of NullPointerExceptions in your code. It provides a clean and concise way to handle values that might or might not be present and reduces the risk of missing important checks in your code.