java null check

simuruk wiki
 1 public class NullCheck {
 2     private class School {
 3         private ClassRoom classRoom;
 4 
 5         public ClassRoom getClassRoom() {
 6             return classRoom;
 7         }
 8     }
 9 
10     private class ClassRoom {
11         private Student student;
12 
13         public Student getStudent() {
14             return student;
15         }
16     }
17 
18     private class Student {
19 
20     }
21     
22     // 깊은 의심 패턴
23     public void deepDoubtPattern(School school) {
24         if (school != null) {
25             if (school.getClassRoom() != null) {
26                 Student student = school.getClassRoom().getStudent();
27             }
28         }
29     }
30 
31     // Optional의 map을 사용한 null check 및 object 가져오기
32     public void useOptional(School school) {
33         Student student = Optional.ofNullable(school)
34                 .map(School::getClassRoom)
35                 .map(ClassRoom::getStudent)
36                 .orElse(null);
37     }
38     
39 }

참고 링크

- https://multifrontgarden.tistory.com/131