Use a classpath resource or kill your application’s portability

Here is the secret way to kill your application’s portability — and by portable, I mean across different computers, let alone operating systems:  Hardcode all your paths.

That’s it.  That very quickly kills portability.  It’s easy to accomplish, too.  Simply refer to all your configuration files, for example, by fully qualified pathname, like this:

    "C:\\Documents and Settings\\FOO\\Perforce_FOO\\PATHS_CHANGED_FOR_ANONYMITY\\RefDataConfig.xml");

The above snippet is something I’m battling with to get unit tests working in my project. Naturally it doesn’t work for me because “FOO” isn’t my username nor is my Perforce sandbox “Performance_FOO” because, again, “FOO” isn’t my username.

This unit test won’t work across machines using the same OS, and our brethren using Macs or Linux boxes are completely hosed.

Don’t hardcode any paths in your application!

In Java, use a classpath resource.   This gives you portability.  It also allows a Configuration Management team the ability to package all required resources into a single artifact for better version control.

The safest way to get a classpath resource would be to use your current classloader to find the resource.

// Well-behaved Java programs set the thread's current classloader when running in a
// multi-classloader environment.  You see this when you write containers of any type.
// or another way... sufficient for most cases

Leave a comment

You must be logged in to post a comment.