[Refactoring 2ํ] Chapter 6-3 ๋ณ์ ์ถ์ถํ๊ธฐ
๋ฆฌํฉํฐ๋ง 2ํ์ ๋ณด๊ณ ์ ๋ฆฌํ ๊ธ๋ก, ์๋ต๋ ๋ถ๋ถ์ด ์๊ฑฐ๋ ์๋ชป ์ดํดํ ๋ถ๋ถ์ด ์์ ์ ์์ต๋๋ค.
๊ฐ๋ ๊ณผ ์์น
ํํ์์ ์ด๋ฆ์ ๋ถ์ด๊ณ ์ถ์ ๋ ๋ณ์ ์ถ์ถ์ ํ๋ค. ํ์ฌ ํจ์ ์์์๋ง ์๋ฏธ๊ฐ ์๋ค๋ฉด ๋ณ์๋ก ์ถ์ถํ๋ ๊ฒ์ด ์ข๋ค. ๊ทธ๋ฐ๋ฐ ํจ์๋ฅผ ๋ฒ์ด๋ ๋์ ๋ฌธ๋งฅ์์๊น์ง ์๋ฏธ๊ฐ ๋๋ค๋ฉด ํจ์๋ก ์ถ์ถํ๋ ๊ฒ์ด ์ข๋ค. ๊ทธ๋์ผ import ํด์ ์ฌ๊ธฐ์ ๊ธฐ์ ๊ณตํต ๋ก์ง์ ์ฌ์ฉํด ์ค๋ณต์ ์ค์ผ ์ ์๊ธฐ ๋๋ฌธ์ด๋ค. (DRY)
์ฝ๋ ์์
๋ฆฌํฉํ ๋ง ์
... return order.quantity * order.itemPrice - Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 + Math.min(order.quantity * order.itemPrice * 0.1, 100);
๋ฆฌํฉํ ๋ง ํ
... const basePrice = order.quantity * order.itemPrice; const quantityDiscount = Math.max(0, order.quantity - 500) * order.itemPrice * 0.05; const shipping = Math.min(order.quantity * order.itemPrice * 0.1, 100); return basePrice - quantityDiscount + shipping;
3์ค์ง๋ฆฌ ์ฝ๋๊ฐ 4์ค์ด ๋์์ง๋ง ์ฝ๋ ์ดํด๋ ๋ณ์๋ช ์ผ๋ก ์ธํด ํจ์ฌ ์ฌ์์ก๋ค. ๐
์ ์ฐจ
- ์ถ์ถํ๋ ค๋ ํํ์์ ๋ถ์์ฉ์ ์๋์ง ํ์ธํ๋ค.
- ๋ถ๋ณ ๋ณ์(const)๋ฅผ ํ๋ ์ ์ธํ๊ณ ์ด๋ฆ์ ๋ถ์ด๊ณ ์ฝ๋๋ฅผ ์ฎ๊ธด๋ค.
- ์๋ณธ ํํ์์ ์ ์๋ฅผ ์ญ์ ํ๋ค.
ํด๋์ค ์์์์ ๋ณ์ ์ถ์ถ (๋ฉ์๋ ์ถ์ถ)
ํด๋์ค ๋ฌธ๋งฅ ์์์์ ์ผ์ด์ค๋ฅผ ์ดํด๋ณด์.
๋ฆฌํฉํ ๋ง ์
class Order { constructor(aRecord) { this._data = aRecord } get quantity() { return this._data.quantity; } get itemPrice() { return this._data.itemPrice; } get price() { return this.quantity * this.itemPrice - Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 + Math.min(order.quantity * order.itemPrice * 0.1, 100); } }
๋ฆฌํฉํ ๋ง ํ
์ด ์์๋ฅผ ๋ณด๋ฉด ํด๋์ค ์์์๋ ๋ณ์๋ก ์ถ์ถํ๋ ค๋ ๋ถ๋ถ์ด price ๋ฉ์๋ ๋ฒ์๋ฅผ ๋์ด์ Order ํด๋์ค ์ ์ฒด์ ์ ์ฉ๋๋ค. ํด๋์ค ์ ์ฒด์ ์ํฅ์ ์ค ๋๋ ๋ณ์๊ฐ ์๋ ๋ฉ์๋๋ก ์ถ์ถํ๋ ๊ฒ์ ๊ถ์ฅํ๋ค.
class Order { constructor(aRecord) { this._data = aRecord } get quantity() { return this._data.quantity; } get itemPrice() { return this._data.itemPrice; } get price() { return this.basePrice - this.quantityDiscount + this.shipping; } get basePrice() { return this.quantity * this.itemPrice } get quantityDiscount() { return Math.max(0, this.quantity - 500) * this.itemPrice * 0.05; } get shipping() { return Math.min(this.basePrice * 0.1, 100);} }
๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก๐ก
- ์ฝ๋๋ฅผ ์งค ๋๋, ํด๋น ์ฝ๋๊ฐ ์ํ ๋ฒ์์ ๋ฌธ๋งฅ๊น์ง ๋๊ฒ ๊ณ ๋ฏผํ์.
- ๊ฐ์ฒด๋ ํน์ ๋ก์ง๊ณผ ๋ฐ์ดํฐ๋ฅผ ์ธ๋ถ์ ๊ณต์ ํ๋ ค ํ ๋ ๊ณต์ ํ ์ ๋ณด๋ฅผ ์ค๋ช ํด์ฃผ๋ ์ ๋นํ ํฌ๊ธฐ์ ๋ฌธ๋งฅ์ด ๋์ด์ค๋ค. ๋ฉ์น๊ฐ ํฐ ํด๋์ค์์ ๊ณตํต ๋์์ ๋ณ๋ ์ด๋ฆ์ผ๋ก ๋ฝ์๋ด์ ์ถ์ํํด๋๋ฉด ๊ทธ ๊ฐ์ฒด๋ฅผ ๋ค๋ฃฐ ๋ ์ฝ๊ฒ ํ์ฉํ ์ ์์ด ๋งค์ฐ ์ ์ฉํ๋ค.