Showing posts with label code style. Show all posts
Showing posts with label code style. Show all posts

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.

Thursday 12 July 2007

Program Identifier Naming Conventions

Microsoft 1975 Charles Simonyi's explication of the Hungarian notation identifier naming convention. What to say ? Most people thinks that they need to prefix program identifier (say variable, member...) with the system type. For boolean prefix with 'b' like bDone. For int prefix with 'i' like iCount. That's stupid to be so close to the system type. The thing that is important it's the meaning, count, or index, not the hard system type that can be changed. Let's read these: I’m Hungary Hungarian Notation Cleaner, more elegant, and harder to recognize Dropping the 'I' from interface names?

Wednesday 20 June 2007

No brackets !

Let's have:


if (condition)
doSomething();

And later, add doOtherThing() method to the condition.

if (condition)
doSomething();
doOtherThing();

And later, it appends. Ooops. I forgot the brackets.
So, I don't know why it is not required in every languages, BUT you MUST always use brackets.

if (condition) {
doSomething();
}

And then

if (condition) {
doSomething();
doOtherThing();
}

This time I didn't forget the brackets 8-))