반응형
가독성 높이는 습관 - Null
null 이란?
형용사 1. 전문 용어
아무 가치 없는
a null result 아무 가치 없는 결과
The Billion Dollar Mistake
- Charles Antony Richard Hoare (Tony hoare)
- https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/
Null References: The Billion Dollar Mistake
Tony Hoare introduced Null references in ALGOL W back in 1965 "simply because it was so easy to implement", says Mr. Hoare. He talks about that decision considering it "my billion-dollar mistake".
www.infoq.com
Null 문제 (1)
/* NullPointerException */
boolean hasText(String text) {
return text.length() == 0 ? false : true;
}
/* NPE solution */
boolean hasText(String text) {
if (!text == null)
return text.length() == 0 ? false : true;
return false;
}
Null 문제 (2)
String addBracket(String text) {
return "{" + text + "}";
}
// other function
String result = addBracket(null);
System.out.println(result);
- 출력결과 : {null}
String addBracket(String text) {
// Add solution
if (!text == null)
return "{" + text + "}";
return "{}";
}
// other function
String result = addBracket(null);
System.out.println(result);
- 출력결과 : {}
잠재적인 버그
- 1. 클라이언트 → 서버 : (null 파라미터) 괄호 붙여줘
- 2. 클라이언트 ← 서버 : return "{null}" // 이와 같은 비정상값 응답
- 3. 클라이언드 : 정상 판단, 다음 동작 수행
정리
- null 이란 아무런 값도 존재하지 않는 상태
- NullPointerException 발생시킴
- 매번 회피 로직을 넣어야 안전
- 가끔은 전혀 의도하지 않는 방향으로 동작
반응형
'cs > java-spring-boot' 카테고리의 다른 글
[Zero-base] 9-10. Optional 살펴보기 + Java 8 : functional interface (0) | 2022.03.16 |
---|---|
[Zero-base] 9-9. null 핸들링 (0) | 2022.03.16 |
[Zero-base] 9-7. enum (0) | 2022.03.16 |
[Zero-base] 9-6. 캡슐화 (0) | 2022.03.16 |
[Zero-base] 9-5. 이름짓기 (0) | 2022.03.16 |