As I work with Coldfusion 9, I can’t help but keep comparing it to PHP, and I get annoyed by some of the small differences.

One thing that I really have been getting annoyed with lately is checking if a variable is defined.  In most cases you could do a simple check, is it empty? However Coldfusion will puke all over itself if you do an isNull() check on a variable that is ‘not defined’. You really have to know the difference it seems between an empty value, vs a variable that has no defined value (to me they are both null/void).

In PHP, this would be a no brainer to check if it was null / empty by doing a simple string comparisson. (Then again PHP doesn’t care if a variable has been defined before you try to use it, which some people hate, but others find very convenient).

Anyway, on to the example…

Example (if our portlet has no value for renderRequest.getRemoteUser() ):

<cfset raw_userid = renderRequest.getRemoteUser() />
<cfif IsNull(raw_userid)>
   It is Null.<br />
</cfif>

The above would simply error out, as you cannot check something that is undefined. Below is the proper way to handle such a scenario with the approach:

<cfset raw_userid = renderRequest.getRemoteUser() />
<cfparam name="raw_userid" default="0">
<cfinvoke component="core.liferay-functions" method="checkIfLogin" returnvariable="userId">
	<cfinvokeargument name="userid" value="#raw_userid#">
</cfinvoke>


2 Comments to “Coldfusion and checking if a variable is Defined”

  1. Sally Amis | August 3rd, 2011 at 4:03 AM

    You need to read the manual before slagging off a programming language.

    The function isDefined checks if a variable exists or not.

  2. Jakub | August 10th, 2011 at 12:53 AM

    @Sally Amis,
    I’ve tried isDefined, it doesn’t work as I would expect coming from a PHP background where I could check if it has a value. It would result in an error that I would have to catch. I’ve read the manual, and I like to bitch, so yes, I’m ‘slagging off’

    😉

Leave a Comment