SRO SRO - 1 year ago 66
C# Question

TDD : Any pattern for constant testing?

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
    constant value from
    and you get two files :
    for the traces and
    for the logs...

  • You change
    from 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
    and 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
    from, say
    but automated mail alerts are still sent to

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
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 :)

Answer Source

The only way I can test a change for a constant (!) value is to make that constant an application setting

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:

const decimal LITERS_PER_HOGSHEAD = 238.480942392;

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.

public class AppSettings
    public const decimal GILLS_PER_HOMER = 1859.771248601;

    public string HelpdeskPhone
        get { // pulled from config and cached at startup }

    public int MaxNumberOfItemsInAComboBox
        get { return 3; }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download