728x90
비어있다고해서 특별히 취급할 이유는 없음.
=> 클라이언트는 이 null 상황을 처리하는 방어 코드를 추가로 작성해야 한다. ( 코드복잡도 + 널 익셉션 발생 가능성)
=> 객체가 0개일 가능성이 거의 없는 경우 몇 년후에 발견할수도있음
빈 컨테이너를 할당하는 비용이 있으니 Null보다 낫다?
=> 성능 저하의 주범이라고 확인되지 않는한 이정도 성능 차이는 신경 쓸 수준이 아님(빠른 프로그램보다 견고한 프로그램을 작성하라)
=> 빈 컬렉션, 배열은 굳이 새로 할당하지 않고도 반환할수 있음(빈 불변 객체 반환)
=> Collections.emptyList , Collections.emptySet, Collections.emptyMap 사용
public List<Cheese> getCheeses(){
return new ArrayList<>(cheesesInStock);
}
/*최적화*/
public List<Cheese> getCheeses(){
return cheesesInStock.isEmpty()?Collections.emptyList() //빈 불변 객체 사용
:new ArrayList<>(cheesesInStock);
}
public Cheese[] getCheeses(){
return cheeseInStock.toArray(new Cheese[0]);
}
//최적화
public static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
public Cheese getCheeses(){
return CheeseInStock.toArray(EMPTY_CHEESE_ARRAY);
}
'JAVA' 카테고리의 다른 글
item 57) 지역변수의 범위를 최소화하라 (0) | 2021.03.20 |
---|---|
interrupt vs notify (0) | 2021.03.16 |
item 53) 가변인수는 신중히 사용하라 (0) | 2021.03.12 |
HashMap 의 capacity와 load factor (0) | 2020.12.27 |
ThreadLocal (0) | 2020.11.22 |