3
\$\begingroup\$

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> 
<cfelse>
    <cfset idInfopage= url.idInfopage>
</cfif>
\$\endgroup\$
2
  • 1
    \$\begingroup\$ What version of CF are you running? \$\endgroup\$ Commented Feb 4, 2013 at 16:20
  • \$\begingroup\$ I am using MX7 at the moment. \$\endgroup\$ Commented Feb 4, 2013 at 16:21

1 Answer 1

12
\$\begingroup\$

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 />

<cfelse>
    <cfset idInfopage = 0 />

</cfif>

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] />
        </cfif>
    </cfloop>

    <cfreturn 0 />
</cffunction>
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.