Combine Functions into Class, ์ฌ๋ฌ ํจ์๋ฅผ ํด๋์ค๋ก ๋ฌถ๊ธฐ๋ฅผ ์์๋ณด์.
์์ฝ
์ฝ๋
function base(aReading) {...}
function taxableCharge(aReading) {...}
function calculateBaseCharge(aReading) {...}
class Reading {
base() {...}
taxableCharge() {...}
calculateBaseCharge() {...}
}
๋ฐฐ๊ฒฝ
- ๊ณตํต ๋ฐ์ดํฐ๋ฅผ ์ค์ฌ์ผ๋ก ๊ธด๋ฐํ๊ฒ ์ฎ์ฌ์๋ ํจ์ ๋ฌด๋ฆฌ๋ฅผ ๋ฐ๊ฒฌํ๋ฉด ํด๋์ค๋ก ๋ฌถ๋ ๊ฒ์ด ์ข๋ค.
- ํด๋์ค๋ก ๋ฌถ์ผ๋ฉด ํจ์๋ค์ด ๊ณต์ ํ๋ ๊ณตํต ํ๊ฒฝ์ ๋ช ์์ ์ผ๋ก ๋๋ฌ๋ผ ์ ์๋ค.
- ๊ฐ ํจ์์ ์ ๋ฌ๋๋ ์ธ์๋ ์ค์ผ ์ ์๋ค.
- ํด๋์ค ๋ง๊ณ ๋ณํ ํจ์๋ก ๋ฌถ๋ ๊ฒฝ์ฐ๋ ์๋๋ฐ, ์ด๋ ๋ค์์ ์์๋ณด์.
์ ์ฐจ
- ํจ์๋ค์ด ๊ณต์ ํ๋ ๊ณตํต ๋ฐ์ดํฐ ๋ ์ฝ๋๋ฅผ ์บก์ํํ๋ค.
- ์ด๊ฒ ์๋์ด ์์ผ๋ฉด ๋งค๊ฐ๋ณ์ ๊ฐ์ฒด ๋ง๋ค๊ธฐ๋ถํฐ ํ๋ค.
- ๊ณตํต ๋ ์ฝ๋๋ฅผ ์ฌ์ฉํ๋ ํจ์ ๊ฐ๊ฐ์ ์ ํด๋์ค๋ก ์ฎ๊ธด๋ค.
- ์ด๋ ๊ณตํต ๋ ์ฝ๋๋ฅผ ๋ฉค๋ฒ๋ ํธ์ถ๋ฌธ์ ์ธ์์์ ์ ๊ฑฐํ๋ค.
- ๋ฐ์ดํฐ ์กฐ์ ๋ก์ง์ ํจ์๋ก ์ถ์ถํ์ฌ ํด๋์ค๋ก ์ฎ๊ธด๋ค.
์์
reading = {customer: "ivan", quantity: 10, month: 5, year: 2017};
// client 1
const aReading = acquireReading();
const baseCharge = baseRate(aReading.month, aReading.year) * aReading.quantity;
// client 2
const aReading = acquireReading();
const base = (baseRate(aReading.month, aReading.year) * aReading.quantity);
const taxableCharge = Math.max(0, base - taxThreshold(aReading.year));
// client 3
const aReading = acquireReading();
const basicChargeAmount = calculateBaseCharge(aReading);
function calculateBaseCharge(aReading) {
return baseRate(aReading.month, aReading.year) * aReading.quantity;
}
- 1, 2, 3์์ ๊ธฐ๋ณธ ์๊ธ ๊ณ์ฐ ๊ณต์์ด ๋๊ฐ๋ค.
- ๊ทธ๋ ๋ค๊ณ 3์์ ์ฌ์ฉํ ์ต์์ ์ฝ๋๋ฅผ 1, 2์์ ์ฌ์ฉํ๊ฒ ํ๋ ๊ฒ์ด ์ณ์๊น?
- ๋ฐ์ดํฐ ๊ทผ์ฒ์ ๋๋ ๊ฒ ๋ง๋ค.
- ๊ทธ๋ ๋ค๋ฉด ํด๋์ค๋ค.
class Reading {
constructor(data) {
this._customer = data.customer;
this._quantity = data.quantity;
this._month = data.month;
this._year = data.year;
}
get customer() {
return this._customer;
}
get quantity() {
return this._quantity;
}
get month() {
return this._month;
}
get year() {
return this._year;
}
get baseCharge() {
return baseRate(this.month, this.year) * this.quantity;
}
get taxableCharge() {
return Math.max(0, this.baseCharge - taxThreshold(this.year));
}
}
// client 1
const rawReading = acquireReading();
const aReading = new Reading(rawReading);
const baseCharge = aReading.baseCharge;
// client 2
const rawReading = acquireReading();
const aReading = new Reading(rawReading);
const taxableCharge = aReading.taxableCharge;
// client 3
const rawReading = acquireReading();
const aReading = new Reading(rawReading);
const taxableCharge = aReading.taxableCharge;