defensive-copy
์๋ฏธ
๋ฐฉ์ด์ ๋ณต์ฌ.
์ด๋ค ์ทจ์ฝ์ ์ ๋ง๊ธฐ ์ํ ๋ณต์ฌ ๋ฐฉ๋ฒ?
์ทจ์ฝ์
TOCTOU(Time Of Check / Time Of Use)
public final class Period {
private final Date start;
private final Date end;
public Period(Date start, Date end) {
if (start.compareTo(end) > 0) {
throw new IllegalArgumentException("start๊ฐ end๋ณด๋ค ๋ฆ์ผ๋ฉด ์๋๋ค");
}
this.start = start;
this.end = end;
}
public Date getStart() { return start; }
public Date getEnd() { return end; }
start.compareTo(end) > 0
ํด๋น ์ฝ๋ validation ์ดํ์Date end
๋ฅผ ์์ ํ ์ ์์.Time of Check
ํน์ ์ฌ์ฉ ์์ ์
Date start
orDate end
๋ฅผ ์ธ๋ถ์์ ์์ ํ ์ ์์.๊ฐ์ ์ฃผ์๊ฐ์ ๊ณต์ ํ๋ ์ธ์คํด์ค ์ด๋.
๊ทธ๋ฌ๋ฉด ์์์น ๋ชปํ ๊ฒฐ๊ณผ๊ฐ ์ด๋๋จ.
๊ฒฐ๊ณผ์ ์ผ๋ก๋
final class Period
๋ก ์ ์ธํ์ด๋ immutableํ ํด๋์ค๊ฐ ์ ํ ์๋.
์ฌ์ฉํ๋ ์ด์
์ทจ์ฝ์ ์ ๊ธฐ๋ฐ์ผ๋ก ์๊ฐํด๋ณผ ๋, ๋ฐฉ์ด์ ๋ณต์ฌ๋, ์ธ์คํด์ค๋ฅผ ์์ฑํ ๋, ๋งค๊ฐ๋ณ์๋ฅผ ๋ฐ๋ ๊ฐ์ฒด๋ฅผ ์๋ก์ด ๊ฐ์ฒด๋ก ๊ฐ์ธ์ ๋ณต์ฌํ๋ ๋ฐฉ๋ฒ์ธ๋ฏ.
์ฆ ์์ฑ๋๋ ๊ฐ์ฒด์์ ์ฐธ์กฐํ๊ณ ์๋ ๋ฉค๋ฒ ๊ฐ์ฒด์, ์ธ๋ถ์์ ๋ค์ด์ค๋ ๊ฐ์ฒด์ ์์กด์ฑ์ ๋์ด์ฃผ๊ธฐ ์ํจ.
ํด๊ฒฐ ๋ฐฉ๋ฒ
public Period(Date start, Date end) {
this.start = new Date(start.getTime()); // defensive copy
this.end = new Date(end.getTime()); // defensive copy
if (this.start.compareTo(this.end) > 0) {
throw new IllegalArgumentException("start๊ฐ end๋ณด๋ค ๋ฆ์ผ๋ฉด ์๋๋ค");
}
}
new Date()
๊ฐ์ฒด์ ์์ฑ์๋ก ์๋ก์ด ์ธ์คํด์ค๋ฅผ ์์ฑ.์ธ๋ถ ์ฐธ์กฐ๋ฅผ ๋์ -> defensive copy
์ฐธ๊ณ
Last updated
Was this helpful?