์๋ฐ์์ ํ๋ก๊ทธ๋๋ฐํ ๋ ์ธ์ ๋ ์กฐ์ฌํด์ผ ํ๋ ๊ฒ์ NullPointerException์ด๋ค.
์ค์ ๋ก ์ต๊ทผ ์ค๋ฌด์์ null ์ฒดํฌ๋ฅผ ๊ผผ๊ผผํ ์ํ๋ค๊ฐ ์ด์์์ ์๋ฌ๊ฐ ์ฐํ๋ ์ฌํ๊ฐ ๋ฐ์ํ๋ค๐ฑ
๊ทธ๋ฆฌ๊ณ List์ null ์ธ์ง์ ๊ฐ์ฒด๊ฐ ๋น์๋์ง๋ฅผ ๋ชจ๋ ํ์ธํด์ค์ผ ํ ์ผ์ด ์๊ฒผ๋๋ฐ, Spring์์ ์ ๊ณตํ๋ CollectionUtils์ ์ฐ๋ฉด ํ ๋ฒ์ ์ฒดํฌํ ์ ์๋ค๋ ๊ฒ์ ์๊ฒ ๋์๋ค. ๊ทธ๋์ ๊ทธ ๋ด์ฉ์ ์ ๋ฆฌํ๊ณ ์ ํ๋ค.
1. null vs empty
์ฐ์ null๊ณผ empty์ ์ฐจ์ด์ ๋ํด ์ ๋ฆฌํด๋ณด์.
์๋ ๊ทธ๋ฆผ์ null๊ณผ empty์ ์ฐจ์ด๋ฅผ ์์ฃผ ์ ์ค๋ช ํด์ฃผ๋ ์งค์ด๋ค.
์ผ์ชฝ ์นธ์ ๋ณด๋ฉด ํด์ง์ ์ฃผ์ ๋ด์ฉ๋ฌผ์ธ ํฐ ๋ถ๋ถ(๋ฐ์ดํฐ)๊ฐ ์๊ณ , ํด์ง๋ฅผ ๋ด๊ณ ์๋ ํด์ง์ฌ(๊ฐ์ฒด)๋ ์๋ ์ํ์ด๋ค.
์ค๋ฅธ์ชฝ ์นธ์ ๋ณด๋ฉด ํด์ง์ฌ(๊ฐ์ฒด) ์กฐ์ฐจ ์๋ ์ํ์ด๋ค.
null
- ์ด๋ค ๊ฐ์ฒด ์ฐธ์กฐ๊ฐ ์ด๋ค ์ธ์คํด์ค๋ ๊ฐ๋ฆฌํค๊ณ ์์ง ์์ ์ํ
- ์ค์ ๊ฐ์ฒด๊ฐ ๋ฉ๋ชจ๋ฆฌ์ ์กด์ฌํ์ง ์์
String str = null;
System.out.println(str.length()); // NullPointerException ๋ฐ์
List<String> list = null;
System.out.println(list.size()); // NullPointerException ๋ฐ์
System.out.println(list.isEmpty()); // NullPointerException ๋ฐ์
- null ์ํ์์ ๋ฉ์๋๋ฅผ ํธ์ถํ๋ฉด `NullPointerException`์ด ๋ฐ์ํ๋ค.
empty
- ๊ฐ์ฒด๋ ์กด์ฌํ์ง๋ง, ๊ทธ ๋ด์ฉ์ด ๋น์ด ์๋ ์ํ
String str = "";
System.out.println(str.length()); // 0
List<String> list = new ArrayList<>();
System.out.println(list.size()); // 0
System.out.println(list.isEmpty()); // true
2. CollectionUtils
์์ธ ์ํฉ ๋ฐฉ์ด๋ฅผ ์ํด null ์ธ ๊ฒฝ์ฐ์ empty์ธ ๊ฒฝ์ฐ ๋ ๋ค ๊ฒ์ฌํด์ผ ํ๋ ๊ฒฝ์ฐ๊ฐ ์๊ธฐ๊ฒ ๋๋ค.
์๋์ ๊ฐ์ด ๋ง์ด ์ฐ๊ฒ ๋ ๊ฒ์ด๋ค.
AS-IS
- null ์ธ ๊ฒฝ์ฐ์ empty์ธ ๊ฒฝ์ฐ ๋ ๋ค ๊ฒ์ฌํด์ผ ํ๋ค.
- null์ ๋ํด .isEmpty()๋ฅผ ๋ฐ๋ก ํธ์ถํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ๋ฏ๋ก, ์๋์ฒ๋ผ ์์๋ฅผ ์ฃผ์ํด์ผ ํ๋ค.
if (list != null && !list.isEmpty()) {
...
}
์ด๊ฑธ ํ ๋ฒ์ ์ฒ๋ฆฌํ ์ ์๋ ๊ฒ์ด ์๋ค. springframework์์ ์ ๊ณตํ๋ CollectionUtils ํด๋์ค์ด๋ค.
List, Set, Map ๊ณผ ๊ฐ์ Collection ์๋ฃ ๊ตฌ์กฐ์ ์ ์ฉํ ๋ฉ์๋๋ค์ ์ ๊ณตํ๋ค.
* ์ด๋ฏธ Spring ํ๋ก์ ํธ๋ฅผ ์ฌ์ฉํ๊ณ ์๋ค๋ฉด ๋ณ๋๋ก ์ถ๊ฐํ ํ์๊ฐ ์๋ค.
import org.springframework.util.CollectionUtils;
CollectionUtils
Check whether the given Collection contains the given element instance. Enforces the given instance to be present, rather than returning true for an equal element as well.
docs.spring.io
- `isEmpty()` : null ์ด๊ฑฐ๋ empty์ธ ๊ฒฝ์ฐ ๋ชจ๋๋ฅผ ๊ฒ์ฌํ์ฌ, ๊ฒฐ๊ณผ ๊ฐ์ boolean์ผ๋ก ๋ฆฌํดํ๊ณ ์๋ค.
TO-BE
- null ์ธ ๊ฒฝ์ฐ์ empty์ธ ๊ฒฝ์ฐ๋ฅผ ํ ๋ฒ์ ๊ฒ์ฌํ ์ ์๋ค.
- NullPointerException์ ๋ฐฉ์งํ ์ ์๋ค.
List<String> list1 = null;
List<String> list2 = new ArrayList<>();
if (CollectionUtils.isEmpty(list1)) { // true
...
}
if (CollectionUtils.isEmpty(list2)) { // true
...
}
ํ์ง๋ง ์ฝ๋์ ๋ฐฉ์ด๋ฅผ ์ํด ` CollectionUtils.isEmpty()`๋ฅผ ๋ฌด์ง์ฑ์ผ๋ก ๋จ๋ฐํ๋ฉด ์๋๋ค.
null๋ง ํ์ธํ๊ณ ์ถ์ ๊ฒฝ์ฐ๋ ์๊ธฐ ๋๋ฌธ์ ์ ๋ฐ์ ธ์ ๊ทธ๋ด ๊ฒฝ์ฐ์๋ `list != null`๋ง ์ฐ๋ ๊ฒ์ด ์ข๋ค.