I have the following code, but it somehow looks a bit redundant. As I am new to ColdFusion, I am not sure how to optimize it. Can someone suggest an alternative?

<cfparam name="url.idInfopage" default="0">
<cfif  not isNumeric(url.idInfopage)><cfset url.idInfopage= 0></cfif>

<cfif isDefined("stElement.idInfopage") and isNumeric(stElement.idInfopage)>
    <cfset idInfopage= stElement.idInfopage>
    <cfif  idInfopage is ""><cfset idInfopage= 0></cfif> 
    <cfset idInfopage= url.idInfopage>
  • 1
    \$\begingroup\$ What version of CF are you running? \$\endgroup\$ – Busches Feb 4 '13 at 16:20
  • \$\begingroup\$ I am using MX7 at the moment. \$\endgroup\$ – user160820 Feb 4 '13 at 16:21

You could re-write it something like this:

<cfif StructKeyExists(stElement,'idInfoPage') AND isNumeric(stElement.idInfopage)>
    <cfset idInfopage = stElement.idInfopage />

<cfelseif StructKeyExists(Url,'idInfoPage') AND isNumeric(Url.idInfopage)>
    <cfset idInfopage = Url.idInfopage />

    <cfset idInfopage = 0 />


Notes on the changes:

If you have a lot of code like this, it might make sense to create a function, something like:

<cfset idInfopage = getNumberOrZero('idInfopage',stElement,Url) />

Then implemented as:

<cffunction name="getNumberOrZero" returntype="numeric" output=false
    hint="Loops through structs (args 2..n) looking for number; else return 0">
    <cfargument name="Key" type="String" required />
    <cfset var i = 0 />

    <cfloop index="i" from=2 to=#ArrayLen(Arguments)#>
        <cfif StructKeyExists(Arguments[i],Arguments.Key)
            AND isNumeric(Arguments[i][Arguments.Key])
            <cfreturn Arguments[i][Arguments.Key] />

    <cfreturn 0 />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.