網頁

2018/10/6

Java 8 用Optional來檢查null 範例二

練習使用Optional來避免NullPointerException

User

public class User {

    private Integer id;
    private String name;
    private Integer age;

    public User(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

}

OptionalUserUser內容幾乎一樣,只是getter會以Optional的方式回傳。注意此為錯誤用法。Optional主要用在一般方法的回傳值,不應用在類別成員、方法或建構式傳入參數、POJO getter等

OptionalUser

public class OptionalUser {

    private Integer id;
    private String name;
    private Integer age;

    public OptionalUser(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Optional<Integer> getId() {
        return Optional.ofNullable(id);
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Optional<String> getName() { // return Optional. wrong use 
        return Optional.ofNullable(name);
    }
    public void setName(String name) {
        this.name = name;
    }
    public Optional<Integer> getAge() { // return Optional. wrong use 
        return Optional.ofNullable(age);
    }
    public void setAge(Integer age) {
        this.age = age;
    }

}

UserService用來取得UserOptionalUser的資料。

UserService

public class UserService {

    private List<User> userList = null;
    private List<OptionalUser> optionalUserList = null;

    public UserService() {
        userList = Arrays.asList(
                new User(1, "John", null), 
                new User(2, null, 17)
            );
        optionalUserList = Arrays.asList(
                new OptionalUser(1, "John", null),
                new OptionalUser(2, null, 17)
            );
        
    }

    public User getUserById(Integer id) {
        for (User user : userList) {
            if(user.getId() == id) {
                return user;
            }
        }
        return null;
    }

    public Optional<OptionalUser> getOptionalUserById(Integer id) {
        for (OptionalUser optionalUser : optionalUserList) {
            if(optionalUser.getId().orElse(-1) == id) {
                return Optional.ofNullable(optionalUser);
            }
        }
        return Optional.empty();
    }

    public boolean isAdult(OptionalUser ou) {
        return ou.getAge().filter(a -> a >= 18).map((a) -> {
            System.out.println(ou.getName().get() + " is adult");
            return true;
        }).orElseGet(() -> {
            System.out.println(ou.getName().get() + " is not adult");
            return false;
        });
    }

}

Main

public class Main {
    
    private static final int DEFAULT_AGE = 1;

    public static void main(String[] args) throws Exception {
        
        UserService service = new UserService();
        
        // 使用if來檢查null
        User user = service.getUserById(2);
        if(user != null) {
            Integer age = user.getAge();
            if(age == null) {
                age = DEFAULT_AGE;
            }
            if(user.getName() == null) {
                user.setName("Anonymouse");
            }
            if(age >= 18) {
                System.out.println(user.getName() + " is adult");
            } else {
                System.out.println(user.getName() + " is not adult");
            }
        } else {
            throw new Exception("No user found");
        }

        // 使用Optional       
        OptionalUser ou = service.getOptionalUserById(2).orElseThrow(() -> new Exception("No user found"));
        String name = ou.getName().orElseGet(()->{
            ou.setName("Anonymouse");
            return ou.getName().get();
        });
        
        System.out.println(service.isAdult(ou));
    }
    
}

參考:

沒有留言:

張貼留言