코드로 대화하기 – Null 만날지 말지~!
Null 만날지 말지~!
null은 항상 java에서 골치꺼리이다. Class에서 null을 보기 싫다면 의도적으로 null이 되지 못하게 해라.
class Cart { private List<String> cartList; public Cart() { cartList = new ArrayList(); } public void addItem(String item) { if (item == null || item.isEmpty() == true) { throw new EmptyItemException("item == null || item.isEmpty() == true"); } cartList.add(item); } public void addAllItem(List<String> cartList) { if (cartList == null || cartList.size() == 0) { throw new EmptyItemException("item == null || item.isEmpty() == true"); } this.cartList.addAll(cartList); } public List<String> getCartList() { return cartList; } }
코드에서 cartList는 null이 될수 없다. 그래서 getCartList()를 호출하더라도 안심하고 null 체크 없이 사용이 가능하다. null을 만날지 말지 고민하지 말고 만나기 싫으면 의도적으로 못 만나게 해라. 틈이 보이면 만날수 밖에 없다.
댓글 남기기