Watch your signatures.

Try to avoid methods that have arguments of the same type.

It is easy to have a bug if people call the arguments in the wrong order.

For example, suppose you have a calculator method that takes in arguments running total, amount, discount, and tax. So when called with the arguments, for example, (100.00, 12.00, 0.20, 0.05), one might expect to take 20% off of the $12 amount, add 5% tax to it, add that to the current running total of $100, and return the new running total. So it would return, in this case, 110.50. But if running_total and amount are both of type money, then another developer might mistakenly call this method using arguments in a different order, such as (12.00, 100.00, 0.20, 0.05). This set of arguments would compute differently and give a result of 92.40.

If each argument had its own type, then passing in variables out of error would give a type error, avoiding this problem. For example, instead of a generic money type, maybe running total is of type SubtotalMoney, and the amount is AmountMoney.

Another solution is to avoid passing in the running total and instead of making that its own object so that it would already know its running total. Thus you could call running_total.add(amount, discount, tax).

Alternatively, one could use named arguments, which is another good practice.

The main point is to make it hard for other developers to make a mistake, so you reduce the chance of bugs occurring down the line.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: