Revisiting Variables


The last tag we'll discuss is <cfparam>. You won't use this tag here, but in preparation for the next chapters, I'll explain what this tag is and how it is used.

Earlier in this chapter, you used a function named IsDefined(), which is used to check whether a variable exists. You used IsDefined() to simply check for a variable's existence, but what if you wanted to create a variable with a default value if it did not exist? You could do something similar to this:

 <cfif NOT IsDefined("FirstName")>  <cfset FirstName="Ben"> </cfif> 

Why would you want to do this? Well, as a rule, you should not include data validation code in the middle of your core code. This is bad practice for several reasons, the most important of which are that it helps create unreliable code, makes debugging difficult, and makes code reuse very difficult. So, best practices dictate that all variable validation occur before your core code. If required variables are missing, throw an error, redirect the user to another page, or do something else. If optional variables are missing, define them and assign default values. Either way, by the time you get to your core code, you should have no need for variable checking of any kind. It should all have been done already.

And thus the type of code I just showed you.

<cfparam> has several uses, but the most common use is simply a way to shortcut the previous code. Look at the following:

 <cfparam name="FirstName" default="Ben"> 

When ColdFusion processes this line, it checks to see whether a variable named FirstName exists. If it does, the tag is ignored and processing continues. If, however, the variable doesn't exist, it will be created right then and there and assigned the value specified in default. So by using <cfparam>, you can ensure that after that tag has been processed, one way or another the variable referred to exists. And that makes writing clean code that much easier.

TIP

<CFPARAM> can be used to check for (and create) variables in specific scopes, including URL and FORM. This can greatly simplify the processing of passed values, as you will see in the coming chapters.




Macromedia Coldfusion MX 7 Web Application Construction Kit
Macromedia Coldfusion MX 7 Web Application Construction Kit
ISBN: 321223675
EAN: N/A
Year: 2006
Pages: 282

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net