SRO SRO - 2 months ago 8
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
    LogCompleteFileName
    constant value from
    L:\LOGS\MyApp.log
    to
    \\Traces\App208.txt
    and you get two files :
    \\traces\App208.txt
    for the traces and
    \\traces\App208.txt.log
    for the logs...

  • You change
    TransactionTimeout
    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
    SleepTimeInMinutes
    from
    1
    to
    10
    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
    CompanyName
    from, say
    Yahoo
    to
    Microsoft
    but automated mail alerts are still sent to
    alert@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 :)

Answer

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; }
    }
}
Comments