Utility Function: IfElse()
- November 8, 2008 5:30 AM
- ColdFusion, Utility Function
- Comments (0)
I don't know about you, but I hate having to write out simple if-else code bits in CF. Until they come out with a good operator like JS has (something?something:something), CF needs a simplification.
<cffunction name="IfElse" access="public" output="false" returntype="Any">
<cfargument name="test" type="boolean" required="true" />
<cfargument name="whenTrue" type="any" required="true" />
<cfargument name="whenFalse" type="any" required="true" />
<cfif ARGUMENTS.test>
<cfreturn ARGUMENTS.whenTrue />
<cfelse>
<cfreturn ARGUMENTS.whenFalse />
</cfif>
</cffunction>
<cfargument name="test" type="boolean" required="true" />
<cfargument name="whenTrue" type="any" required="true" />
<cfargument name="whenFalse" type="any" required="true" />
<cfif ARGUMENTS.test>
<cfreturn ARGUMENTS.whenTrue />
<cfelse>
<cfreturn ARGUMENTS.whenFalse />
</cfif>
</cffunction>
Seems pointless, but which would you rather read?
<!--- Classic, 5 lines --->
<cfif true>
<cfset x = "dog" />
<cfelse>
<cfset x = "cat" />
</cfif>
<!--- Version 2, 4 lines --->
<cfset x = "cat" />
<cfif true>
<cfset x = "dog" />
</cfif>
<!--- My Way, 1 line --->
<cfset x = IfElse(true, "dog", "cat") />
<cfif true>
<cfset x = "dog" />
<cfelse>
<cfset x = "cat" />
</cfif>
<!--- Version 2, 4 lines --->
<cfset x = "cat" />
<cfif true>
<cfset x = "dog" />
</cfif>
<!--- My Way, 1 line --->
<cfset x = IfElse(true, "dog", "cat") />