Common Absolute Paths Anti-Pattern

Some projects I’ve worked on in the past assume that certain files can always be found at an absolute path, eg ‘c:\program files\some cool library\library.dll’. Such files may be dependencies, or deployment target locations. This is a situation to be avoided!

The main reason this is so bad is that you may not actually have control over such paths when your application gets deployed. For example, many IT operations departments use ‘C:’ just for the Windows O/S, and put all other files on a secondary drive (e.g. for backup purposes). If your project assumes absolute paths, such problems may not arise until you finally reach production.

However there are other problems, like what happens when you want to work on 2 versions of the app at the same time (e.g. trunk, and branch)?

But there is good news – you don’t need to hard code absolute paths into your system! Alternatives are:

Use relative paths. As an example, setup your source control directory structure such that you always know where your dependencies can be found relative to your project’s source code. (This may mean you save third-party binaries in source-control but this is not a sin!)

Use deploy-time configuration. Get your build environment to generate environment-specific distribution files where parameterised paths are expanded to absolute paths at the last moment.

Use environment variables, like path. This is a ‘last-chance’ option since it is system-wide, rather than application-wide in scope, but stops you having to hard code paths in your application at least.

To check that a project I’m working on isn’t using absolute paths, I tend to do one of the following things

– Have 2 copies of the development tree checked out on my machine. Switch between them occasionally and check nothing breaks.

– Have my continuous integration and ‘development test’ environments specifically use different paths to that of the development team.

%d bloggers like this: