null을 반환하는 메서드를 사용할 때는 항상 방어 코드를 넣어줘야 한다.
빈 배열이나 컬렉션을 만들고 할당하는데 드는 성능적인 비용이 걱정된다면.
• 할당을 하지 않고 바로 반환할 수 있다.
• 비어있는 불변 객체를 반환할 수 있다.
public class CheeseStore {
private final List<Cheese> cheesesInStock = new ArrayList<>();
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
public CheeseStore(Cheese... initialCheeses) {
for (Cheese cheese : initialCheeses) {
addCheese(cheese);
}
}
private void addCheese(Cheese cheese) {
cheesesInStock.add(cheese);
}
public List<Cheese> getCheese() {
return cheesesInStock.isEmpty() ? null : new ArrayList<>(cheesesInStock);
}
// public Cheese[] getCheeseArray() {
// return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
// }
}
public class CheeseExample {
public static void main(String[] args) {
CheeseStore cheeseStore = new CheeseStore();
List<Cheese> cheese = cheeseStore.getCheese();
if (cheese != null && !cheese.isEmpty()) {
System.out.println("We have cheese: " + cheese);
} else {
System.out.println("We have no cheese");
}
}
}