Constants are beautiful people – they can hold in a unique place a value that is used everywhere in your code. Changing that value requires only one simple modification.
Life is cool.
Well, this is the promise. Reality is sometime different :
- You change the
LogCompleteFileNameconstant value fromL:\LOGS\MyApp.logto\\Traces\App208.txtand you get two files :\\traces\App208.txtfor the traces and\\traces\App208.txt.logfor the logs… - You change
TransactionTimeoutfrom 2 to 4 minutes and you still get a timeout after 2 minutes (after spending the day, you find out that you also have to change the timeout of the DBMS and the timeout of the transaction manager…). - You replace
SleepTimeInMinutesfrom1to10and you see no change (after an hour or so, you find out that the constant’s name was misleading : the granularity is not the minute but the millisecond…). - Even more subtle: you change
CompanyNamefrom, sayYahootoMicrosoftbut automated mail alerts are still sent toalert@yahoo.com…
Creating a constant is a contract. You are telling your readers that whenever they change the value, it will still works the way they think it should be.
Nothing less.
Of course, you need to test that you are not misleading your readers. You have to make sure that the implied contract is right.
How do you achieve that with TDD? I’m just stuck with that. The only way I can test a change for a constant (!) value is to make that constant an application setting… Should I have to conclude that the const keyword should be avoided when I think that the value can and will change?
How are you testing your (so called) constants using TDD?
Many thanks in advance 🙂
All of the uses you listed in the question sound like application settings, not constants, to me. A constant is a value that is, well, constant, such as:
Edited to add: Hopefully this is more helpful than my flippant answer. I usually create an AppSettings class. Some of the properties in this class are pulled from the config file, some are settings that I don’t expect to change, and some could be constants.