In code we often need to make use of constant values. It is good practice to use named constants rather than literal values, but what is a good technique for managing constants in an object oriented ColdFusion application? One technique is to break your constants down into separate files that relate to their particular area. For example you might have a set of files:
Inside each file you would define the constants for that area. For example, for the products.cfm file you may write:
<cfscript> // Define the product constant namespace. structGet("constant.product"); // Product status constants. constant.product.STATUS_ACTIVE = 1; constant.product.STATUS_INACTIVE = 2; constant.product.STATUS_ARCHIVED = 3; // Other product related constants here, etc. constant.product.IS_FEATURE = 1; constant.product.IS_SPECIAL = 2; </cfscript>
Here you can use the structGet() function to create a “namespace” for your constants. This means that if you have identical constant names in different areas then they will not overlap.
Then, wherever you need to use the constants you can include these directly into your components:
<cfcomponent output="false"> <cfinclude template="/constants/global.cfm"> <cfinclude template="/constants/products.cfm"> <!--- Functions here... ---> </cfcomponent>
This would cause the constants to all be loaded into the component’s variables scope. You could them use them in a function as follows:
<cffunction name="isActive" output="false"> <cfreturn getStatusId() eq constant.product.STATUS_ACTIVE> </cffunction>
This does not appear to be a particularly object oriented technique but seems a little nicer that some of the alternatives, such as referencing an external scope (eg constants stored in the application scope) or passing/injecting a “Constants” object into other objects that require it.
What do you think? How do you handle constants in ColdFusion components?