π 1. nullμ λ°ννλ κ²½μ°
맀μ₯ μμ μΉμ¦ λͺ©λ‘μ λ°ννλ λ©μλλ₯Ό μ΄ν΄λ³΄μ.
private final List<Cheese> cheeseInStock = ...;
/**
* @return 맀μ₯ μμ λͺ¨λ μΉμ¦ λͺ©λ‘μ λ°ννλ€.
* λ¨, μ¬κ³ κ° νλλ μλ€λ©΄ nullμ λ°ννλ€.
*/
public List<Cheese> getCheeses() {
return cheeseInStock.isEmpty() ? null
: new ArrayList<>(cheeseInStock);
}
컬λ μ μ΄λ λ°°μ΄ κ°μ 컨ν μ΄λ(container)κ° λΉμμ λ nullμ λ°ννλ λ©μλλ₯Ό μ¬μ©ν λλ©΄ νμ μλμ κ°μ λ°©μ΄ μ½λλ₯Ό λ£μ΄μ€μΌ νλ€.
List<Cheese> cheeses = shop.getCheese();
if(cheeses != null && cheeses.contains(Cheese.STILTON))
System.out.println("μ°Ύμλ€ μ€νΈν΄");
볡μ‘νλ€. κ·Έλ¦¬κ³ λ§μ½ nullμ μ²λ¦¬νμ§ μλλ€λ©΄, NullPointExceptionμ΄ λ°μν μ μλ€. nullμ λ°ννλ APIλ μ¬μ©νκΈ° μ΄λ ΅κ³ μ€λ₯ μ²λ¦¬ μ½λλ λμ΄λλ€.
λλ‘λ λΉ μ»¨ν μ΄λλ₯Ό ν λΉνλ λ°λ λΉμ©μ΄ λλ nullμ λ°ννλ μͺ½μ΄ λ«λ€λ μ£Όμ₯λ μλ€. νμ§λ§, μ±λ₯ λΆμ κ²°κ³Ό μ΄ ν λΉμ΄ μ±λ₯ μ νμ μ£Όλ²μ΄λΌκ³ νμΈλμ§ μλ ν, μ΄ μ λμ μ±λ₯ μ°¨μ΄λ μ κ²½ μΈ μμ€μ΄ λͺ» λλ€. λν, λΉ μ»¬λ μ κ³Ό λ°°μ΄μ κ΅³μ΄ μλ‘ ν λΉνμ§ μκ³ λ λ°νν μ μλ€.
π 2. nullμ λ°ννμ§ μλ κ²½μ°
μμ λ©μλλ μλμ κ°μ΄ λ°κΏ μ μλ€.
// λΉ μ»¬λ μ
λ°ν
public List<Cheese> getCheeses() {
return new ArrayList<>(cheeseInStock);
}
λΉ μ»¬λ μ ν λΉμ΄ μ±λ₯μ λμ λκ² λ¨μ΄λ¨λ¦°λ€λ©΄ μλμ κ°μ΄ λ°κΏ μ μλ€.
// λΉ μ»¬λ μ
μ΄ λ§€λ² μλ‘ ν λΉλμ§ μλλ‘ νλ κ²
public List<Cheese> getCheeses() {
return cheeseInStock.isEmpty() ? Collections.emptyList()
: new ArrayList<>(cheeseInStock);
}
λ°°μ΄λ λ§μ°¬κ°μ§λ€.
// κΈΈμ΄κ° 0μΌ μλ μλ λ°°μ΄μ λ°ν
public Cheese[] getCheeses() {
return cheesesInStock.toArray(new Cheese[0]);
}
// λΉ λ°°μ΄μ λ§€λ² μλ‘ ν λΉνμ§ μκ³ λ°ννλ λ°©λ²
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
public Cheese[] getCheeses() {
return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
}
ν΄λΉ κΈμ Joshua Bloch λμ 'Effective Java 3/E'λ₯Ό μ°Έκ³ νμμ΅λλ€.