Constants in Code

I was recently looking at some VBA code (not mine) that was accessing lots of different Word templates. The code contained many full absolute paths to the template files, as literal strings: “H:\foo\bar\…\…\Templates\”. These happened to be on a network drive, not a local one. It struck me that this is a maintenance problem waiting to happen: if the drive or the path change, there are many occurrences of the literal to change. Also, anyone writing new code needs to be aware of the correct value for this path.

The Golden Rule here is: never have more than one occurrence of a literal value. (We can make exceptions for 0, 1 and immutable values such as the number of months in a year).

Within a project (i.e. template), the simple solution is to have a module that contains only constants: let’s call it ‘Constants’. This contains const declarations for all literal strings:

Const drive As String = "C:"
Const temppath As String = "\...\...\My Documents\Temp"
Const dotpath As String = "\...\...\...\Microsoft\Templates"

Now, we’re often going to want to construct a full file path from these strings plus a file name. So the module can also contain ‘constructor’ functions for different types of file:

Function TempFile(name As String) As String
      TempFile = drive + temppath + "\" + name
End Function

In other modules, we can then write things like:

ActiveDocument.SaveAs (TempFile("Working.doc"))

All we need to know is that it’s a temporary file.

We can even be nice and make the suffix optional:

Function Template(name As String) As String
    Template = drive + dotpath + "\" + name
    If Not Mid(Template, Len(Template) - 3) = ".dot" Then
        Template = Template + ".dot"
    End If
End Function

So now we could just write:

Documents.Add (Template("Work_basic"))

If the path changes, then we just change the single const declaration in the Constants module.

Indeed, we might want different modules for different kinds of constant: FileSystem, Messages, Financial, and so on.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

January 2009
    Feb »

%d bloggers like this: