I am helping a friend design a program in Smalltalk (never coded in Smalltalk before, I only know c++), where I need to read the transactions from a txt file and implement it. There might be cases where we might encounter different currencies. In that case, I need to take the currency exchange rate from a table that has date|currency1-currency2|currency2-currency1 exchange rate. So I modeled my class like this:

  1. Read the file for the transaction.
  2. Do an addition or subtraction of the amount.

While adding or subtracting, there might be different currencies, say Canadian dollar, dollar. Hence if the current account has dollar, I might need to do an conversion to dollar from Canadian dollar using operator overloading.

So, I have a base class Currency, derived class Canadian dollar & dollar. my operator over loading looks like this.

Currency& operator+(Currency& c) {
  local_var + c.to_canadian_dollar();
}

uint32 to_canadian_dollor() {
  return local_var * er.conversion_rate(); **<-- I need to pass date for the exchange rate function to get the exchange rate for today's date.**
}

The problem is that the I need to pass the date for the conversion rate, but I cannot pass the date via operator overloading.

Does anyone else have a better design? or any language feature in small talk that will let me pass the date without breaking the chain? I can make the design look ugly by setting the date before the transaction. But just curious, if there is a better design that I could learn.

有帮助吗?

解决方案

Smalltalk doesn't have operator overloading. Because it doesn't have operators. In C++, you have operators and methods as distinct, but kinda similar, entities. In Smalltalk, you just have methods. Period. So when you see '+' in Smalltalk code, it is not an operator (because they don't exist in Smalltalk). It's a message send. The left side object acts as the receiver, and the '+' method is sent to it with the right side object as the sole argument.

So what you could do, would be to define a new numeric object, which encapsulates your date dynamic data in it.

You don't say which Smalltalk you're using, but most flavors use the double dispatch pattern to enable transcendental math between "math aware" objects. If you provide some more detail on your problem, maybe I'll provide some more detail via an example here...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top