I have a function that looks up a user in a database by their email and returns a struct containing their ID, email, and hashed password. But since ColdFusion lacks a null/nil/none type, I can't figure out what to return if a user doesn't exist.
My first solution was to return false
, then just use if(user == false)
to see if a user exists, but with both ==
and is
, ColdFusion will try to convert a valid user struct to a boolean and throw an error when it can't.
My second solution was to just return;
without a value, but then my check becomes if(isDefined("foo"))
. In my opinion, that looks quite ugly, and makes refactoring a bit trickier since the variable name is now also in a string...
Is there a clean way of returning a "nothing found" value in ColdFusion?
CF has isNull()
since CF9, e.g.:
<cffunction name="getUser">
<cfargument name="userID">
<cfquery name="qUser">
SELECT * FROM users where userID = <cfqueryparam value="#userID#">
</cfquery>
<cfif qUser.recordCount>
<cfreturn {name=qUser.name}>
</cfif>
</cffunction>
<cfset var user = getUser(1)>
<cfif isNull(user)>
<!-- user not found -->
<cfelse>
Welcome #user.name#
</cfif>