2012-05-01 2 views
0

私はTest Driven Development: By Exampleを読んでいます。私は第13章にあります。第12章と第13章はオブジェクトにPlusオペレーションを導入しました。 Moneyオブジェクトは、他のオブジェクトによってプラスすることができる。Moneyオブジェクト。Moneyを計算するためにSumとBankクラスが必要なのはなぜですか?

著者はソリューションに2つのクラス(BankSum)と1つのインターフェイス(IExpression)を追加しました。これは最終的な解決策のクラス図です。例えば

Class diagram

Moneyストア額および通貨10ドル、5バーツ、20 CHF。 PlusメソッドはSumオブジェクトを返します。

public class Money : IExpression 
{ 
    private const string USD = "USD"; 
    private const string CHF = "CHF"; 

    public int Amount { get; protected set; } 

    public string Currency { get; private set; } 

    public Money(int value, string currency) 
    { 
     this.Amount = value; 
     this.Currency = currency; 
    } 

    public static Money Dollar(int amount) 
    { 
     return new Money(amount, USD); 
    } 

    public static Money Franc(int amount) 
    { 
     return new Money(amount, CHF); 
    } 

    public Money Times(int times) 
    { 
     return new Money(this.Amount * times, this.Currency); 
    } 

    public IExpression Plus(Money money) 
    { 
     return new Sum(this, money); 
    } 

    public Money Reduce(string to) 
    { 
     return this; 
    } 

    public override bool Equals(object obj) 
    { 
     var money = obj as Money; 

     if (money == null) 
     { 
      throw new ArgumentNullException("obj"); 
     } 

     return this.Amount == money.Amount && 
      this.Currency == money.Currency; 
    } 

    public override string ToString() 
    { 
     return string.Format("Amount: {0} {1}", this.Amount, this.Currency); 
    } 
} 

Sumコンストラクタ引数に由来する2つのMoneyオブジェクトを格納します。 Reduce - それは新しいMoneyオブジェクトを返す1つの方法Reduce(2つのオブジェクトの追加量により、新しいオブジェクトを作成)

public class Sum : IExpression 
{ 
    public Money Augend { get; set; } 

    public Money Addend { get; set; } 

    public Sum(Money augend, Money addend) 
    { 
     this.Augend = augend; 
     this.Addend = addend; 
    } 

    public Money Reduce(string to) 
    { 
     var amount = this.Augend.Amount + this.Addend.Amount; 

     return new Money(amount, to); 
    } 
} 

Bankは一つの方法を持っています。それは、入力の引数のReduceメソッドを呼び出すだけです。

public class Bank 
{ 
    public Money Reduce(IExpression source, string to) 
    { 
     return source.Reduce(to); 
    } 
} 

IExpressionMoneySumによって実装されるインターフェースです。

public interface IExpression 
{ 
    Money Reduce(string to); 
} 

これは私の質問です。

  1. Bankこの段階では解決策はありません。なぜ私はそれが必要なのですか?
  2. 私はのようにMoneyPlusの中にMoneyオブジェクトを作成して返すことができるので、Sumが必要なのはなぜですか?
  3. 銀行と合計の目的は何ですか? (今、私には意味がありません)
  4. Reduce私はメソッド名として奇妙に思えます。それは良い名前だと思いますか? (お勧めします)
+0

あなたがこの質問に近いと投票した場合。なぜそれが終わると思うのか教えてください。 :) ありがとうございました。 – Anonymous

+0

私は投票に投票しました。あなたはまだ血の本を終えていないので、それは良い質問だとは思わない。 – duffymo

+0

だから、私に彼に従うことを提案し、私が本を終えたときに彼がこのようにした理由を理解するでしょう。 (私は失礼な言い方をしたくありません。次の章に進む前に、私はいつも理由を探して話題に明瞭にするために尋ねます。 – Anonymous

答えて

2

お読みください。ケントベックは非常にスマートな男です。彼はそのような例を作った理由は非常にありますが、それは後で明らかになるか、それは貧弱な解決策です。

map-reduceが最終目標である場合、「Reduce」は非常に良い名前です。

関連する問題