Using Regular Expressions to build ColdFusion getters and setters
I’m always looking for ways to make my life a little easier when writing code, and to take the monotony out of the equation wherever I can. I know there is lots of back-and-forth about whether this method should or should not be used in ColdFusion, but I feel that for the minor incovenience of running a reg ex, creating getters and setters in my CFCs/Objects just make sense if just for the very fact of encapsulation. Plus if you need to alter anything that occurs during a “set” operation, nothing outside of the object is broken when you make the change within your object. Anyway, back to business:
This regular expression can be used in Eclipse (my current IDE) and will convert something that looks like:
<cfset variables.firstName = "" /> <cfset variables.lastName = "" />
into
<cffunction name="getfirstName" output="false" access="public" returntype="any"> <cfreturn variables.firstName /> </cffunction> <cffunction name="setfirstName" output="false" access="public" returntype="void"> <cfargument name="val" required="true" /> <cfset variables.firstName = arguments.val /> </cffunction>
The search string is:
<cfset variables.(\w+) = [^>]+>(\r\n)(\t)and the replace string is:
<cffunction name="get$1" output="false" access="public" returntype="any">$2$3$3<cfreturn variables.$1 />$2$3</cffunction>$2$2$3<cffunction name="set$1" output="false" access="public" returntype="void">$2$3$3<cfargument name="val" required="true" />$2$3$3<cfset variables.$1 = arguments.val />$2$3</cffunction>$2$2$
The search string contains a “tab” character at the end. This is really just so I can format the output of the getters and setters, but feel free to modify them however you wish.