tags:

views:

160

answers:

4

Does it make sense to create a constant for the value of a penny? For example, if I needed to decrement an amount by a penny. Do you think it is more readable if the code said:

amount -= Constants.StandardAmounts.Penny

Or should I not even bother and just use .01.

+1  A: 

I would use the constant. Not because the value of a penny will change, but simply for clarity to future maintainers of the application.

EDIT: I guess I would also consider the number of places that this value will be used.

Ed Swangren
A: 

You can even change to for better readability:

amount -= Standards.USCurrency.Penny
Michael Kniskern
+11  A: 

In your specific example, that particular constant does not really make sense. The two likeliest scenarios to subtract a penny are:

  • Fulfill some very specific business/domain logic requirement:

    If so, the constant should not be Penny = .01, but StandardDeduction = .01

  • Handle more arbitrary/fluid maths:

    If so, just use numbers.

In either case, "Penny" is pointless. It does not add any useful information. That's like declaring constant HelloWorld = "HelloWorld". Every programmer who has even a vague idea of what your application is doing (financial calculations) understands what .01 is. Constants should be driven by purpose.

Rex M
A: 

I would put the decrementing into a method and then name that method appropriately (ie stay away from having penny in the title). So for example if you have a supermarket application and every customer gets a 1 penny discount, you can just call DeductCustomerLoyaltyAmount(). This has these advantages:

  1. Anyone reading the code now has a full understanding of why the decrementing is happening.

  2. You can change the decrement value without affecting the meaning of the method.

  3. Your globalisation code (to handle other currencies) is centralised.