Practical .NET
Use Constants and Enums to Improve Readability (and Reduce Maintenance)
If you're not using Const and Enums then you're just making life harder for the next programmer.
I learned a lot from Art Boyd, the first boss I had as a programmer -- sometimes at loud volumes, I admit, but always stuff worth learning. At one point, for example, he called me into his office to complain about some code I'd written. I won't say he "yelled" at me but I will say he "spoke in a highly aggravated manner". He pointed at a line in one of my programs where the number 12 appeared and said, "I thought I told you never to use constants!"
In my defense, I replied that this 12 represented the number of months in a year and, since that wasn't likely to change, I just hardcoded 12 into the statement rather than go to the trouble of declaring a constant. Art sent me back to my terminal to rewrite the code.
Decades later, I realize that Art was right. At the time, I only considered constants from the maintenance point of view: If I hardcoded some value into my application then, should that value ever change, I'd have to track down and change every occurrence (consider the odds that I'll find every occurrence). If I declare a constant and use that constant in my code, I only have to change the value in one place: where I declare the constant.
But, as useful as that feature is from a maintenance point of view, I think that the readability value is even more important. This is why we use enumerated values, of course. Fundamentally, I don't care what number is "really" held in an enumerated value, I just prefer this code:
If Customer.State = CustomerStates.DontSellToThisOneAnyMore Then
to this code:
If Customer.State = 1 Then
Going back to my one-sided argument with Art, using a constant is the difference between this line of code:
For i = 1 to 12
and this line of code:
For month = 1 to NumberOfMonthsInYear
Regardless of the context, the first line of code requires the developer reading it to figure out what the number 12 represents. The second line of code tells the developer exactly what the number represents. What can I say? Art was right.
I still won't create a constant for the number 1, though.
About the Author
Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.