13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

ArithmeticHow do we add two Moneys together? Let’s get the simple case right first, where we have the samecurrency in both Moneys. When you add two Moneys with the same currency together, theresulting Money should have as its amount the sum of the amounts of the first two.Money>>+ aMoney^self speciesamount: amount + aMoney amountcurrency: currencyWe need a Getting Method for the variable “amount” for this to work:Money>>amount^amountWe get the right answer if we’re adding dollars to dollars:| m1 m2 |m1 := Moneyamount: 5currency: #USD.m2 := Moneyamount: 7currency: #USD.m1 + m2 12 USDChange one of the Moneys to a different currency, though, and we get the wrong answer:| m1 m2 |m1 := Moneyamount: 5currency: #USD.m2 := Moneyamount: 7currency: #GBP.m1 + m2 12 USDFive dollars and seven pounds is not twelve dollars. How are we going to keep the simple “+”protocol for arithmetic and still handle the case where we have multiple currencies? The answer isto introduce an Impostor (a modeling pattern) for a Money that defers exchange rate conversions.We’ll give it the Simple Superclass Name of MoneySum.Class: MoneySumsuperclass: Objectinstance variables: moniesThe variable with the Role Suggesting Instance Variable Name “monies” will hold a Collection ofMoneys.We create a MoneySum with a Complete Creation Method:MoneySum class>>monies: aCollection^self new setMonies: aCollectionThe collection is passed on to the Creation Parameter Method:MoneySum>>setMonies: aCollectionmonies := aCollectionWe’ll add a Debug Print Method to MoneySum so we can check our results:<strong>Coding</strong> <strong>Patterns</strong> page 143 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!