Wednesday 16 April 2008

Money money money, bug me honey


Money
int value;
String currency;

Money add(Money initial, Money toAdd) {
int value = initial.getValue() + dogAmount.getValue();
Money money = new AnimalMoney(value, initial.getCurrency())

return money;
}


Everything looks alright, but it's not.

Try to add money using these one :


Money cat = new AnimalMoney(5, "cat");
Money dog = new AnimalMoney(1, "dog");

Money deal = add(cat, dog);


You will obtain 6 values of cat. Does 5 cats plus 1 dog equals 6 cats. I think not.

Always think about the type of what you deal with. Remember your physics lectures when we calculate the result kind, like multiply hours by km per hour.

One solution can be to lower the accessibility of the inner elements. Money value and currency should not be manipulated outside its package. Outside package code must only use helper function to manipulate them.

No comments: