patternModerate
Setting a page number from the URL, with fallbacks
Viewed 0 times
numberthefallbackswithsettingpagefromurl
Problem
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?
As I am new to ColdFusion, I am not sure how to optimize it. Can someone suggest an alternative?
Solution
You could re-write it something like this:
Notes on the changes:
If you have a lot of code like this, it might make sense to create a function, something like:
Then implemented as:
Notes on the changes:
- StructKeyExists is generally recommended over isDefined.
- isNumeric wont return true for empty string.
If you have a lot of code like this, it might make sense to create a function, something like:
Then implemented as:
Code Snippets
<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><cfset idInfopage = getNumberOrZero('idInfopage',stElement,Url) /><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>Context
StackExchange Code Review Q#21389, answer score: 12
Revisions (0)
No revisions yet.