Utility Function: IfElse()

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>

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

 

Comments

Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web.

Learn more about me.

Post a job. Find one. authenticjobs.com

Interested in becoming a sponsor? Contact me.