Making Your ColdFusion Applications More Platform Independent (Part II)

Last Friday, I made a post about writing platform-independent ColdFusion code, and specifically how important it is to be consistent with case when you are naming and referencing files since Unix file systems are case sensitive. The other practice I often see people do which keeps code from being platform independent is hardcoding file separators. The Windows file separator is a “\” (backslash character), however the file separator on Unix file systems is a “/” (forward slash character). The Macintosh file separator is a “:” (colon character), however the OS X file system will let you get away with a Unix-like “/” file separator. If your application needs to construct file paths, and you want your code to be truly platform independent, you will need to take these differences into account.

There are two good ways to make your file separators dynamic. The first is to define the system’s file separator in the Application.cfm file or other file where you keep configuration parameters. For instance, if you add this to your Application.cfm file…

<cfset request.FILE_SEPARATOR = "/" />

… rather than hardcoding slashes throughout your code, you can then simply refer to the request.FILE_SEPARATOR variable.

You can make your life even easier by letting ColdFusion (or, more precisely, Java) figure out what the system’s default file separator is for you with the following function:

function getFileSeparator()
var fileObj = "";
if (isDefined("application._fileSeparator"))
return application._fileSeparator;
fileObj = createObject("java", "");
application._fileSeparator = fileObj.separator;
return getFileSeparator();

This function actually caches the file separator for you the first time you call it so that you are not instantiating a new object each time you call it, however if you prefer to have your calling code do the caching, naturally you can re-factor the function appropriately. The point is that by not hardcoding your file separators, your code is much more platform independent, and much easier to port from one OS to another.