item 54 jihoonKim - JAVA-JIKIMI/EFFECTIVE-JAVA3 GitHub Wiki
// ๋ฐ๋ผ ํ์ง ๋ง ๊ฒ! - ์ฌ๊ณ ๊ฐ ์๋ค๊ณ ํน๋ณ ์ทจ๊ธํ ์ด์ ๋ ์๋ค.
private final List<Cheese> cheesesInStock = ...;
/**
* @return ๋งค์ฅ ์์ ๋ชจ๋ ์น์ฆ ๋ชฉ๋ก์ ๋ฐํํ๋ค.
* ๋จ, ์ฌ๊ณ ๊ฐ ํ๋๋ ์๋ค๋ฉด null์ ๋ฐํํ๋ค.
*/
public List<Cheese> getCheeses() {
return cheesesInStock.isEmtpy() ? null
: new ArrayList<>(cheesesInStock);
}
// client ์ธก์์ null์ ๋ฆฌํดํ๋ ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด์๋ ํญ์ ์ด์ ๊ฐ์ ๋ฐฉ์ด์ฝ๋๋ฅผ ๋ฃ์ด์ค์ผ ํ๋ค.
List<Cheese> cheeses = shop.getCheeses();
if (cheeses != null && cheeses.contains(Cheese.M\ozzarell
...
}
- ์ฑ๋ฅ ์ ํ์ ์ฃผ๋ฒ์ด๋ผ๊ณ ํ์ธ๋์ง ์์๋ค๋ฉด ์ด ์ ๋ ์ฑ๋ฅ ์ฐจ์ด๋ ๊ฑฐ์ ์๋ค.
- ๋น ์ปฌ๋ ์ ๊ณผ ๋น ๋ฐฐ์ด์ ์๋ก ํ ๋นํ์ง ์๊ณ ๋ ๋ฆฌํดํ ์ ์๋ค.
// ๋น ์ปฌ๋ ์
์ ๋ฆฌํดํ๋ ์ฌ๋ฐ๋ฅธ ์
public List<Cheese> getCheeses() {
return new ArrayList<>(cheesesInStock);
}
๋งค๋ฒ ๋๊ฐ์ ๋น '๋ถ๋ณ(immutable)' ์ปฌ๋ ์ ์ ๋ฆฌํดํ์ฌ ์ต์ ํ
- Colections.emptyList()
- Colections.emptySet()
- Colections.emptyMap()
// ์ต์ ํ - ๋น '๋ถ๋ณ(immutable)' ์ปฌ๋ ์
๋ฆฌํด(๊ผญ ํ์ํ ๋๋ง ์ฌ์ฉํ๊ณ , ์ฑ๋ฅ ๊ฐ์ ์ด ๋๋์ง ํ์ธ ํ์)
public List<Cheese> getCheeses() {
return cheesesInStock.isEmtpy() ? Collections.emptyList()
: new ArrayList<>(cheesesInStock);
}
์ฐธ๊ณ )
- ๋ถ๋ณ์ Thread-safeํ๋ค.
- ๋ถ๋ณ์ add์ ๊ฐ์ ๋ณํ๋ฅผ ์๋ํ๋ค๋ฉด UnsupportedOperationException์ด ๋ฐ์ํ ์ ์์ผ๋ฏ๋ก, ์กฐ์ฌํ ์ฌ์ฉํด์ผ ํ๋ค.
// ๊ธธ์ด๊ฐ 0์ผ ์๋ ์๋ ๋ฐฐ์ด์ ๋ฆฌํดํ๋ ์ฌ๋ฐ๋ฅธ ๋ฐฉ๋ฒ
public Cheese[] getCheeses() {
return cheesesInStock.toArray(new Cheese[0]);
}
์ฐธ๊ณ )
- <T> T[] List.toArray(T[] a) ๋ฉ์๋๋ a์ ์ฌ์ด์ฆ๊ฐ ํฌ๋ฉด a ์์ ์์๋ฅผ ๋ด์ ๋ฆฌํดํ๋ค.
- a์ ์ฌ์ด์ฆ๊ฐ List๋ณด๋ค ์์ผ๋ฉด T[] ํ์ ์ ์๋ก ๋ง๋ค์ด ๊ทธ ์์ ์์๋ฅผ ๋ด์ ๋ฐํํ๋ค.
- cheesesInStock์ ์ฌ์ด์ฆ๊ฐ 1 ์ด์์ด๋ฉด ๋ฐฐ์ด์ ์๋ก ์์ฑํด ๋ฆฌํดํ๊ณ , ์ฌ์ด์ฆ๊ฐ 0์ด๋ฉด 0์ธ ๋ฐฐ์ด์ ์๋ก ์์ฑํด ๋ฆฌํดํ๋ค.
// ์ต์ ํ - ๊ธธ์ด 0์ง๋ฆฌ ๋ฐฐ์ด์ ๋ฏธ๋ฆฌ ์ ์ธํด๋๊ณ ๋งค๋ฒ ๊ทธ ๋ฐฐ์ด์ ๋ฐํ(๊ธธ์ด 0์ธ ๋ฐฐ์ด์ ๋ชจ๋ ๋ถ๋ณ)
private static final Cheese[] EMTPY_CHEESE_ARRAY = new Cheese[0];
public Cheese[] getCheeses() {
return cheesesInStock.toArray(EMTPY_CHEESE_ARRAY);
}
์ฐธ๊ณ )
- cheesesInStock์ ์ฌ์ด์ฆ๊ฐ 1 ์ด์์ด๋ฉด ๋ฐฐ์ด์ ์๋ก ์์ฑํด ๋ฆฌํดํ๊ณ , ์ฌ์ด์ฆ๊ฐ 0์ด๋ฉด EMPTY_CHEESE_ARRAY๋ฅผ ๋ฆฌํดํ๋ค.
- array identity๋ฅผ ์ฌ์ฉํ๋ค๋ฉด ๋ฌธ์ ๊ฐ ๋ ์ ์๊ธฐ์, ๋ชจ๋ ๊ณณ์ ์ ์ฝ๋๋ก ์นํํ๋ ๊ฒ์ ์ ํจํ์ง ์๋ค.(https://shipilev.net/blog/2016/arrays-wisdom-ancients/)
๋จ์ํ ์ฑ๋ฅ ๊ฐ์ ๋ชฉ์ ์ผ๋ก toArray์ ๋๊ธฐ๋ ๋ฐฐ์ด์ ๋ฏธ๋ฆฌ ํ ๋นํ๋ ๊ฑด ์คํ๋ ค ์ฑ๋ฅ์ด ๋จ์ด์ง๋ค๋ ์ฐ๊ตฌ ๊ฒฐ๊ณผ๋ ์๋ค.
// ๋์ ์
return cheesesInStock.toArray(new Cheese[cheesesInStock.size()]);
null์ ์์ธ์ฒ๋ฆฌ๊ฐ ํ์ํ๊ธฐ ๋๋ฌธ์, ๋น ๋ฐฐ์ด์ด๋ ๋น ์ปฌ๋ ์ ์ ๋ฆฌํดํ๋ผ.