網頁

2018/8/25

Java 8 用Optional來檢查null

寫Java一陣子都知道,最常出現的錯誤例外就是NullPointerException,而為了避免出現這個例外,所以程式中經常使用if else先判斷物件是否為null後,才會去呼叫物件的方法。

例如下面範例的物件類別為ComputerVideoCard

Computer

public class Computer {

    private VideoCard videoCard;

    public VideoCard getVideoCard() {
        return videoCard;
    }
    public void setVideoCard(VideoCard videoCard) {
        this.videoCard = videoCard;
    }

}

VideoCard

public class VideoCard {

    private String videoCardName;

    public String getVideoCardName() {
        return videoCardName;
    }
    public void setVideoCardName(String videoCardName) {
        this.videoCardName = videoCardName;
    }
}

產生Computer的工廠類。

ComputerFactory

public class ComputerFactory {

    public Computer getComputer() {
        String videoCardName = "Geforce RTX 2080 Ti";

        Computer computer = new Computer();
        VideoCard videoCard = new VideoCard();
        videoCard.setVideoCardName(videoCardName);
        computer.setVideoCard(videoCard);
        return computer;
    }

}

isNivida()方法原本使用if else如下。

Main

public class Main {

    public static void main(String[] args) {
        ComputerFactory factory = new ComputerFactory();
        Computer computer = factory.getComputer();
        System.out.println(isNvidia(computer));
    }
    
    public static boolean isNvidia(Computer computer) {
        if (computer != null) {
            VideoCard videoCard = computer.getVideoCard();
            if (videoCard != null) {
                String videoCardName = videoCard.getVideoCardName();
                if (videoCardName != null) {
                    if (videoCardName.contains("Geforce")) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}

改用Java 8的Optional來寫。

Main

public class Main {

    public static void main(String[] args) {
        ComputerFactory factory = new ComputerFactory();
        Computer computer = factory.getComputer();
        System.out.println(isNvidia(computer));
    }
    
    public boolean isNvidia(Computer computer) {
        return Optional.ofNullable(computer)
                .map(Computer::getVideoCard)  // 若computer不是empty,返回Computer.getVideoCard()
                .map(VideoCard::getVideoCardName)  // 若c.getVideoCard()不是empty,返回VideoCard.getVideoCardName()
                .filter(s -> s.contains("Geforce")).isPresent();  // 若filter()滿足,返回true,否則返回false。
    }

}

還是覺得不好懂,也很不惜慣這種寫法。


參考:

沒有留言:

張貼留言