开发者

Naming constants which are part of a formula

For开发者_StackOverflow中文版 my C++ class, the instructor said he will give a score of zero to any program submitted with magic numbers. He said, even for formulas such as calculating the area of a circle (where it is common knowledge that 3.14159 is the value of Pi, we should either use a const variable or a #define directive to represent Pi and then use that in the formula).

With that said, I'm doing a financial calculation where I am determining the amount of a bill before tax. A snipet from the function is:

mealCostBeforeTax = billAmount / (1.0 + taxRate_);

The taxRate_ is an argument passed to the function as a decimal percent (e.g. 0.08). So in order to determine the amount before the tax, I have to add 1 to the taxRate making it 1.08.

My question is, since to the instructor 1.0 is a magic number. What is an appropriate name for that value?

This leads also to another question. When I am using formulas, is there a resource or a direction I can be pointed with help in understanding what certain constants in functions are called, or what they represent.

For example, when converting a temperature from Celsius to Fahrenheit, the formula is Tf=(9/5)*Tc+32. How does one find out what 9/5 represents as well as the 32. I would assume that 32 is the freezing point of water on the Fahrenheit scale, but that is just a guess. The 9/5 I would imagine is some kind of ratio between the scales, but these are guesses.

Sorry for the wall of text. But I really wanted to write a thorough question so that hopefully others may find it useful.


All in all, I think calling the 1.0 in this formula a magic number is a little extreme. Not every literal number is necessarily a magic number. The point is to make your code readable such that the person looking at it won't have to guess why you picked that number out of thin air.

In this case, I think the solution would be to wrap the calculation in a function instead of trying to come up with a #define for the 1. God help me if I ever see another program where you have a statement like #define one 1 because a programmer is following the letter of the magic number rule and not the intent.

float getPreTaxCost(float totalCost, float taxRate);
{
  return totalAmount / (1.0 + taxRate);
}

Especially for common formulas like converting F to C, this just makes sense. As a rule of thumb, if there is an obvious name for a constant/define that is used in a calculation definitely use it instead of a naked number in the code. However, don't force the issue to extremes.

I'd confirm this assumption with your prof, of course.. They can be pretty pedantic to the point of absurdity because they live in the theory and not the real world and often demand adherence to strict rules because they are rules forgetting the reason behind them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜