Question

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?

Was it helpful?

Solution

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>

OTHER TIPS

returning a blank '' or false works fine.

the trick is in how the return is handled, because most likely you'll do an if isStruct(result) it doesn't matter what you return as long as it is not a structure

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top