2017年10月18日 星期三

[ Java 文章收集 ] An Introduction to Functional Programming in Java 8: Part 2 - Optionals

Source From Here 
Preface 
After we’ve made our first big steps into functional programming in the last post, we will talk about Optionals in today’s part. 

Why do we need Optionals? 
Hand on heart, you also think that null is annoying, don’t you? For every argument which can be null, you have to check whether it is null or not
  1. if(argument == null) {  
  2.     throw new NullPointerException();  
  3. }  
These lines suck! This is a boilerplate that bloats up your code and can be easily forgotten. So how can we fix that? 

Introducing Optionals 
In Java 8, java.util.Optional was introduced to handle objects which might not exist better. It is a container object that can hold another object. The Generic T is the type of the object you want to contain. 
  1. Integer i = 5;  
  2. Optional optinalI = Optional.of(i);  
The Optional class doesn’t have any public constructor. To create an optional, you have to use Optional.of(object) or Optional.ofNullable(object). You use the first one if the object is never, ever null. The second one is used for nullable objects. 

How do optionals work? 
Optional have two states. They either hold an object or they hold null. If they hold an object, Optional are called present, if they hold null, they are called empty. If they are not empty, you can get the object in the Optional by using Optional.get(). But be careful, because a get() on an empty optional will cause a NoSuchElementException. You can check if a optional is present by calling the method Optional.isPresent(). Below is a simple example: 
  1. public void playingWithOptionals() {  
  2.     String s = "Hello World!";  
  3.     String nullString = null;  
  4.   
  5.     Optional optionalS1 = Optional.of(s); // Will work  
  6.     Optional optionalS2 = Optional.ofNullable(s); // Will work too  
  7.     Optional optionalNull1 = Optional.of(nullString); // -> NullPointerException  
  8.     Optional optionalNull2 = Optional.ofNullable(nullString); // Will work  
  9.   
  10.     System.out.println(optionalS1.get()); // prints "Hello World!"  
  11.     System.out.println(optionalNull2.get()); // -> NoSuchElementException  
  12.     if(!optionalNull2.isPresent()) {  
  13.         System.out.println("Is empty"); // Will be printed  
  14.     }  
  15. }  
Common problems when using Optionals 

1. Working with Optional and null 
  1. public void workWithFirstStringInDB() {  
  2.     DBConnection dB = new DBConnection();  
  3.     Optional first = dB.getFirstString();  
  4.   
  5.     if(first != null) {  
  6.         String value = first.get();   
  7.         //...   
  8.     }  
  9. }  
This is just the wrong use of an Optional! If you get an Optional (In the example you get one from the DB), you don’t have to look whether the object is null or not! If there’s no string in the DB, it will return Optional.empty(), not null! If you got an empty Optional from the DB, there would also be a NoSuchElementException in this example. 

2. Using isPresent() and get() 

2.1. Doing something when the value is present 
  1. public void workWithFirstStringInDB() {  
  2.     DBConnection dB = new DBConnection();  
  3.     Optional first = dB.getFirstString();  
  4.   
  5.     if(first.isPresent()) {  
  6.         String value = first.get();   
  7.         //...   
  8.     }  
  9. }  
As I already said, you should always be 100% sure if an Optional is present before you use Optional.get(). You wouldn’t get a NoSuchElementException anymore in the updated function. But you shouldn’t check a optional with the isPresent() + get() combo! Because if you do it like that, you could have used null in the first place. You would replace first.isPresent() with first != null and you have the same result. But how can we replace this annoying if-block with the help of Optionals? 
  1. public void workWithFirstStringInDB() {  
  2.     DBConnection dB = new DBConnection();  
  3.     Optional first = dB.getFirstString();  
  4.   
  5.     first.ifPresent(value -> /*...*/);  
  6. }  
The Optional.ifPresent() method is our new best friend to replace the if. It takes a Function, so a Lambda or method reference, and applies it only when the value is present. If you don’t remember how to use method references or Lambdas, you should read the last part of this series again. You use ifPresent() when you want to do something that produces a side effect. Storing something in the DB and IO are two common examples for side effects. If you don’t need side effects, you shouldn’t use ifPresent(), but map(), which is part of the next section. 

2.2. Returning a Modified Version of the Value 
  1. public Integer doubleValueOrZero(Optional value) {  
  2.     if(value.isPresent()) {  
  3.        return value.get() * 2;  
  4.     }  
  5.   
  6.     return 0;  
  7. }  
In this method, we want to double the value of an optional, if it is present. Otherwise, we return zero. The given example works, but it isn’t the functional way of solving this problem. To make this a lot nicer, we have two function that are coming to help us. The first one’s Optional.map(Function mapper) and the second one’s Optional.orElse(T other)map takes a function, applies it on the value and returns the result of the function, wrapped in an Optional again. If the Optional is empty, it will return an empty Optional again. orElse returns the value of the Optional it is called on. If there is no value, it returns the value you gave orElse(object) as a parameter. With that in mind, we can make this function a one liner. 
  1. public Integer doubleValueOrZero(Optional value) {  
  2.     return value.map(i -> i * 2).orElse(0);  
  3. }  
Using flatMap() 
There is another really cool method that you can use with Optionals. It’s called flatMap(). When you use map on a method that returns an Optional, you basically get an Optional>. But you don’t want two containers abound your object! But you also don’t want to rewrite the method nor do you want to call get() or orElse() two times to get the value. 

This is the reason there is flatMap. It flattens the Optional> to Optional. In our example, we want to divide 2 Integers. But if we divide by zero, we return Optional.empty(). So if we use map and divide, we have a object of type Optional>. That’s the reason we use flatMap here. 
  1. public void showFlatMap() {  
  2.     Optional two = Optional.of(2.0);  
  3.     Optional zero = Optional.of(0.0);  
  4.     two.flatMap(num -> divide(1.0, num)).orElse(0.0); // 0.5  
  5.     zero.flatMap(num -> divide(1.0, num)).orElse(0.0); // 0.0  
  6. }  
  7.   
  8. public Optional divide(Double first, Double second) {  
  9.     if(second == 0.0) {  
  10.        return Optional.empty();  
  11.     }  
  12.   
  13.     return Optional.of(first / second);  
  14. }  
When Should you use Nullable Objects and when Optionals? 
You can find a lot of books, talks and discussions about the question: Should you use null or Optional in some particular case. And both have their right to be used. In the linked talk, you will find a nice rule which you can apply in most of the cases. Use Optionals when “there is a clear need to represent ‘no result’ or where null is likely to cause errors.”. So you shouldn’t use Optionals like this: 
  1. public String defaultIfOptional(String string) {  
  2.     return Optional.ofNullable(string).orElse("default");  
  3. }  
Because a null check is much easier to read. 
  1. public String defaultIfOptional(String string) {  
  2.     return (string != null) ? string : "default";  
  3. }  
You should use Optionals just as a return value from a function. It’s not a good idea to create new ones to make a cool method chain like in the example above. Most of the times, null is enough. 

Conclusion 
That’s it for today! We have played with the Optional class. It’s a container class for other classes which is either present or not present(empty). We have removed some common code smell that comes with Optionals and used functions as objects again. We also discussed when you should use null and when Optionals. In the next part, we will use Streams as a new way to handle a Collection of Objects. 

Supplement 
An Introduction to Functional Programming in Java ... Part 1 - Functions as Objects 
An Introduction to Functional Programming in Java 8: Part 3 - Streams

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...