본문으둜 κ±΄λ„ˆλ›°κΈ°

🌈 Chapter 12: λ“œλ””μ–΄, λ”ν•˜κΈ°

public void testSimpleAddition() {
Money sum = Money.dollar(5).plus(Money.dollar(5));
assertEquals(Money.dollar(10), sum);
}

κ·Έλƒ₯ Money.dollar(10)λ₯Ό λ°˜ν™˜ν•˜λŠ” μ‹μœΌλ‘œ κ°€μ§œ κ΅¬ν˜„μ„ ν•  μˆ˜λ„ μžˆλ‹€. ν•˜μ§€λ§Œ μ–΄λ–»κ²Œ κ΅¬ν˜„ν•΄μ•Ό 할지 λͺ…ν™•ν•˜λ―€λ‘œ λ‹€μŒκ³Ό 같이 ν•˜κ² λ‹€.

// Money
Money plus(Money addend) {
return new Money(amount + addend.amount, currency);
}

이 κ°„λ‹¨ν•œ μ˜ˆμ œμ—μ„œ Bankκ°€ ν•  일은 정말 ν•˜λ‚˜λ„ μ—†λ‹€. 일단 객체만 ν•˜λ‚˜ μžˆλ‹€λ©΄ μ˜€μΌ€μ΄λ‹€.

public void testSimpleAddition() {
// ...
Bank bank = new Bank();
Money reduced = bank.reduce(sum, "USD");
assertEquals(Money.dollar(10), reduced);
}

두 Money의 합은 Expression이어야 ν•œλ‹€.

public void testSimpleAddition() {
// ...
Expression sum = five.plus(five);
Bank bank = new Bank();
Money reduced = bank.reduce(sum, "USD");
assertEquals(Money.dollar(10), reduced);
}

$5λ₯Ό λ§Œλ“œλŠ”κ±΄ κ°„λ‹¨ν•˜λ‹€.

public void testSimpleAddition() {
Money five = Money.dollar(5);
Expression sum = five.plus(five);
Bank bank = new Bank();
Money reduced = bank.reduce(sum, "USD");
assertEquals(Money.dollar(10), reduced);
}

이걸 μ»΄νŒŒμΌν•˜λ©΄ μ–΄λ–»κ²Œ ν•΄μ•Ό ν•˜λ‚˜? Expression μΈν„°νŽ˜μ΄μŠ€κ°€ ν•„μš”ν•˜λ‹€.

// Expression
interface Expression

Money.plus()λŠ” Expression을 λ°˜ν™˜ν•΄μ•Ό ν•œλ‹€.

//Β Money
Expression plus(Money addend) {
return new Money(amount + addend.amount, currency);
}

이건 Moneyκ°€ Expression을 κ΅¬ν˜„ν•΄μ•Ό ν•œλ‹€λŠ” λœ»μ΄λ‹€.

// Money
class Money implements Expression

이제 빈 Bank ν΄λž˜μŠ€κ°€ ν•„μš”ν•˜λ‹€.

// Bank
class Bank

그리고 Bankμ—λŠ” reduce()의 μŠ€ν…μ΄ μžˆμ–΄μ•Ό ν•œλ‹€.

// Bank
Money reduce(Expression source, String to) {
return null;
}

이제 컴파일이 되고, λ°”λ‘œ μ‹€νŒ¨ν•œλ‹€. λ§Œμ„Έ! 진전이닀. κ°„λ‹¨νžˆ κ°€μ§œ ꡬ문을 ν•  수 μžˆλ‹€.

// Bank
Money reduce(Expression source, String to) {
return Money.dollar(10);
}