Nov
12

By: Adam Sroka
11/12/09 5:59 pm UTC
Topic: No Tags

Conventional wisdom says that literal values in code are bad and should be replaced with constant fields. The usual justification is that when you need to change the value it is easier to change the value of the constant than to change the literal in the various places where it appears. This avoids the real issue: why is the value appearing in multiple places?

Constants are a deodorant. Rather than using a literal value in numerous places, which is bad, we empower ourselves to reference a static field in numerous places, which is almost exactly as bad. Perhaps instead we should consider what concept that value represents that needs to be reused all over our code and find a way to encapsulate that responsibility.

(2) Comments
Comments:
2 Comments posted on "Constants Are a Scam"
Marcos Silva Pereira on November 29th, 2009 at 12:32 am

Sometimes is not about have just one place to change, but it’s about readability. Is easy to read/understand ITEMS_AMOUNT than just 10.


asroka on November 29th, 2009 at 2:21 pm

Thanks, Marcos.

It is probably better to say PI = 3.14159265 and then use PI in my calculation. That is called an “explaining variable.” It makes it much clearer what the number means. However, there are a limited number of ways to use pi: volume of a sphere, angular distance, etc. Those things should probably be in one place in my code and not several.

Local explaining variables are an exceptionally good idea. Public constants are likely to violate encapsulation.


Post a comment
Name: 
Email: 
URL: 
Comments: