๊ฐ์ฒด์ ๋ถ๋ณ์ฑ(immutability)์ ์ ์งํ๋ฉด์ ์์ ํ๊ฒ ๋ฐ์ดํฐ๋ฅผ ๊ด๋ฆฌํ๋ ๋ฐฉ๋ฒ์ ๋ํด ๋ค์ ํ๋ฒ ์๊ธฐ์ํค๋ ๋ง์์ผ๋ก, ๋ฐฉ์ด์ ๋ณต์ฌ(Defensive Copy)๋ผ๋ ๊ฐ๋ ์ ๋ค์๊ธ ์ ๋ฆฌํด๋ณผ ํ์์ฑ์ ๋๊ผ์ต๋๋ค. ์๋ณธ ๊ฐ์ฒด์ ๋ถํ์ํ ๋ณ๊ฒฝ์ ๋ฐฉ์งํ๊ณ , ์๊ธฐ์น ์์ ์ฌ์ด๋ ์ดํํธ(Side Effect)๋ฅผ ์ค์ด๊ธฐ ์ํด ๋ฐฉ์ด์ ๋ณต์ฌ๋ฅผ ์ด๋ป๊ฒ ํ์ฉํ ์ ์๋์ง ์ดํด๋ณด๊ฒ ์ต๋๋ค.
๋ฐฉ์ด์ ๋ณต์ฌ(Defensive Copy)๋ ๊ฐ์ฒด์ ์๋ณธ๊ณผ์ ์ฐธ์กฐ๋ฅผ ๋๊ณ ์๋ก์ด ๋ณต์ฌ๋ณธ์ ์์ฑํ์ฌ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ์๋ฏธํฉ๋๋ค. ์ด๋ฅผ ํตํด ์ธ๋ถ์์ ์๋ณธ ๊ฐ์ฒด๋ฅผ ์์ ํ ์ ์๋๋ก ๋ณดํธํ์ฌ, ํ๋ก๊ทธ๋จ์ ์์ ์ฑ์ ๋์ผ ์ ์์ต๋๋ค.
์ธ๋ถ์์ ์ ๋ฌ๋ฐ์ ๊ฐ๋ณ ๊ฐ์ฒด๋ฅผ ๊ทธ๋๋ก ์ ์ฅํ๋ฉด ๋ณด์ ์ทจ์ฝ์ ์ด ๋ฐ์ํ ์ ์์ต๋๋ค. ๋ฐ๋ผ์, ๋ณต์ฌ๋ณธ์ ๋ง๋ค์ด ์ ์ฅํ๋ ๊ฒ์ด ์ค์ํฉ๋๋ค.
import java.util.List;
public class Lotto {
private final List<Integer> numbers;
public Lotto(List<Integer> numbers) {
this.numbers = numbers; // ์ํ: ์๋ณธ ๋ฆฌ์คํธ๋ฅผ ๊ทธ๋๋ก ์ฐธ์กฐํจ
}
}
numbers
๋ฆฌ์คํธ๊ฐ ์ธ๋ถ์์ ๋ณ๊ฒฝ๋๋ฉด,Lotto
๊ฐ์ฒด์ ๋ด๋ถ ๋ฐ์ดํฐ๋ ๋ณํ ์ ์์ต๋๋ค.
import java.util.List;
import java.util.ArrayList;
public class Lotto {
private final List<Integer> numbers;
public Lotto(List<Integer> numbers) {
this.numbers = new ArrayList<>(numbers); // ๋ฐฉ์ด์ ๋ณต์ฌ ์ ์ฉ
}
}
์๋ก์ด
ArrayList
๊ฐ์ฒด๋ฅผ ์์ฑํ์ฌ ์๋ณธ ๋ฐ์ดํฐ๋ฅผ ๋ณต์ฌํจ์ผ๋ก์จ, ์ธ๋ถ์ ๋ณ๊ฒฝ์ด ๋ด๋ถ ๋ฐ์ดํฐ์ ์ํฅ์ ๋ฏธ์น์ง ์๋๋ก ํฉ๋๋ค.
๋ด๋ถ ๋ฐ์ดํฐ๋ฅผ ๊ทธ๋๋ก ๋ฐํํ๋ฉด ์ธ๋ถ์์ ์์ ํ ์ ์๊ธฐ ๋๋ฌธ์, ๋ณต์ฌ๋ณธ์ ๋ฐํํ๋ ๊ฒ์ด ์์ ํฉ๋๋ค.
public List<Integer> getNumbers() {
return numbers; // ์ํ: ์ธ๋ถ์์ numbers ๋ฆฌ์คํธ๋ฅผ ์์ ํ ์ ์์
}
import java.util.Collections;
public List<Integer> getNumbers() {
return Collections.unmodifiableList(numbers); // ๋ถ๋ณ ๋ฆฌ์คํธ ๋ฐํ
}
Collections.unmodifiableList()
๋ฅผ ์ฌ์ฉํ์ฌ ์ฝ๊ธฐ ์ ์ฉ ๋ฆฌ์คํธ๋ฅผ ๋ฐํํ๋ฉด, ์ธ๋ถ์์ ๋ฆฌ์คํธ๋ฅผ ์์ ํ๋ ค๊ณ ํ๋ฉดUnsupportedOperationException
์ด ๋ฐ์ํฉ๋๋ค.
๊ธฐ๋ณธ์ ์ธ ๋ฐฉ์ด์ ๋ณต์ฌ๋ ์์ ๋ณต์ฌ(Shallow Copy)๋ก ์ํ๋๋ฏ๋ก, ๋ฆฌ์คํธ ๋ด๋ถ์ ์์๊ฐ ๊ฐ๋ณ ๊ฐ์ฒด์ผ ๊ฒฝ์ฐ ์์ ์์ฒด๋ ๋ณต์ฌ๋์ง ์์ต๋๋ค. ์ด ๊ฒฝ์ฐ ๊น์ ๋ณต์ฌ(Deep Copy)๋ฅผ ์ ์ฉํด์ผ ํฉ๋๋ค.
import java.util.ArrayList;
import java.util.List;
public class Lotto {
private final List<LottoNumber> numbers;
public Lotto(List<LottoNumber> numbers) {
this.numbers = new ArrayList<>();
for (LottoNumber number : numbers) {
this.numbers.add(new LottoNumber(number)); // ๊น์ ๋ณต์ฌ ์ ์ฉ
}
}
public List<LottoNumber> getNumbers() {
List<LottoNumber> copy = new ArrayList<>();
for (LottoNumber number : numbers) {
copy.add(new LottoNumber(number));
}
return Collections.unmodifiableList(copy);
}
}
๋ฆฌ์คํธ์ ์์๊ฐ ๊ฐ๋ณ ๊ฐ์ฒด๋ผ๋ฉด, ๊ฐ๋ณ ์์๋ ๋ณต์ฌํ์ฌ ์๋ก์ด ๊ฐ์ฒด๋ฅผ ์์ฑํด์ผ ํฉ๋๋ค.
โ๏ธ ๋ถ๋ณ์ฑ(Immutable) ๋ณด์ฅ: ์๋ณธ ๊ฐ์ฒด๊ฐ ๋ณ๊ฒฝ๋์ง ์๋๋ก ๋ณดํธํ ์ ์์ต๋๋ค.
โ๏ธ ์ฌ์ด๋ ์ดํํธ(Side Effect) ๋ฐฉ์ง: ์ธ๋ถ์์ ๋ด๋ถ ์ํ๋ฅผ ๋ณ๊ฒฝํ ์ ์์ผ๋ฏ๋ก, ์๊ธฐ์น ์์ ๋ฒ๊ทธ๋ฅผ ์ค์ผ ์ ์์ต๋๋ค.
โ๏ธ ๋ฉํฐ์ค๋ ๋ ํ๊ฒฝ์์ ์์ : ๊ฐ์ฒด๊ฐ ๋ณ๊ฒฝ๋์ง ์์ผ๋ฏ๋ก, ๋๊ธฐํ ๋ฌธ์ ๋ฅผ ๋ฐฉ์งํ ์ ์์ต๋๋ค.
์ฑ๋ฅ ์ค๋ฒํค๋
๊ฐ๋ ์ฑ ๊ณ ๋ ค
๋ฐฉ์ด์ ๋ณต์ฌ๋ ๋ถ๋ณ์ฑ(immutability)์ ์ ์งํ๊ณ , ๊ฐ์ฒด์ ๋ฌด๊ฒฐ์ฑ์ ๋ณด์ฅํ๋ ์ค์ํ ๊ธฐ๋ฒ์ ๋๋ค. ํนํ, ๊ฐ๋ณ ๊ฐ์ฒด๋ฅผ ๋ค๋ฃฐ ๋ ๋ฐฉ์ด์ ๋ณต์ฌ๋ฅผ ์ ์ ํ ํ์ฉํ๋ฉด ์๊ธฐ์น ์์ ๋ฒ๊ทธ๋ฅผ ๋ฐฉ์งํ๊ณ , ์์ ์ ์ธ ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ต๋๋ค.
์ฌ๋ฌ๋ถ์ ์ฝ๋์์๋ ๋ฐฉ์ด์ ๋ณต์ฌ๋ฅผ ์ ์ฉํด ๋ณด์ธ์! ๐
---