If Statements


If statements are a fundamental part of most development languages. Though the syntax varies from one language to the next, the basic concepts and options are the same. If statements are used to create conditions that are evaluated, enabling you to perform actions based on the result.

The conditions passed to if statements always evaluate to TRUE or FALSE, and any condition that can be expressed as a TRUE / FALSE (or YES / NO) question is valid. Here are some examples of valid conditions:

  • Is today Monday?

  • Does variable FirstName exist?

  • Were any rows retrieved from a database?

  • Does variable one equal variable two?

  • Is a specific word in a sentence?

More complex conditions (multiple conditions) are allowed, too:

  • Is today Sunday or Saturday?

  • Was a credit card number provided, and if yes, has it been validated?

  • Does the currently logged-in user have a first name of Ben and a last name of Forta, or a first name of Nate and a last name of Weiss?

The common denominator here is that all these conditions can be answered with trUE or FALSE, so they are all valid conditions.

NOTE

In ColdFusion, the words trUE and FALSE can be used when evaluating conditions. In addition, YES can be used in lieu of trUE, and NO can be used in lieu of FALSE. It is also worth noting that all numbers are either trUE or FALSE: 0 is FALSE, and any other number (positive or negative) is trUE.


Basic If Statements

ColdFusion if statements are created using the <cfif> tag. <cfif> takes no attributes; instead, it takes a condition. For example, the following <cfif> statement checks to see whether a variable named FirstName contains the value Ben:

 <cfif FirstName IS "Ben"> 

The keyword IS is an operator used to test for equality. Other operators are supported, too, as listed in Table 9.1.

Table 9.1. CFML Evaluation Operators

OPERATOR

SHORTCUT

DESCRIPTION

EQUAL

IS, EQ

Tests for equality

NOT EQUAL

IS NOT, NEQ

Tests for nonequality

GREATER THAN

GT

Tests for greater than

GREATER THAN OR EQUAL TO

GTE

Tests for greater than or equal to

LESS THAN

LT

Tests for less than

LESS THAN OR EQUAL TO

LTE

Tests for less than or equal to

CONTAINS

 

Tests whether a value is contained within a second value

DOESN'T CONTAIN

 

Tests whether a value is not contained within a second value


As seen in Table 9.1, most CFML operators have shortcut equivalents that you can use. The IS operator used in the previous code example is actually a shortcut for EQUAL, and that condition is:

 <cfif FirstName EQUAL "Ben"> 

To test whether FirstName is not Ben, you could use the following code:

 <cfif FirstName IS NOT "Ben"> 

or

 <cfif FirstName NEQ "Ben"> 

or

 <cfif FirstName NOT EQUAL "Ben"> 

or even

 <cfif NOT FirstName IS "Ben"> 

In this last snippet, the NOT operator is used to negate a condition.

Ready to try <cfif> yourself? What follows is a simple application that checks to see whether today is the weekend (see Figure 9.1). Save the file as if1.cfm, and execute in from within Dreamweaver or your Web browser (if the latter then the URL to use will be http://localhost:8500/ows/9/if1.cfm if the integrated Web server is being used). The output is shown in Figure 9.1.

Listing 9.1. if1.cfm
 <!--- Name: if1.cfm Author: Ben Forta (ben@forta.com) Description: Demonstrate use of <cfif> Created: 12/1/2004 ---> <html> <head>  <title>If 1</title> </head> <body> <!--- Is it the weekend? ---> <cfif DayOfWeek(Now()) IS 1>  <!--- Yes it is, great! --->  It is the weekend, yeah! </cfif> </body> </html> 

Figure 9.1. <cfif> statements can be used to display output conditionally.


TIP

Don't forget to create the 9 directory under ows; all the code created in this chapter should go in that directory.


The code in Listing 9.1 should be self-explanatory. A comment header describes the code, and the standard HTML <head> and <body> tags are used to create the page. Then comes the <cfif> statement:

 <cfif DayOfWeek(Now()) IS 1> 

As you already have seen, Now() is a function that returns the current system date and time. DayOfWeek() is a function that returns the day of the week for a specified date (a variable, a literal, or another function). DayOfWeek(Now()) returns the current day of the week: 1 for Sunday, 2 for Monday, 3 for Tuesday, and so on. The condition DayOfWeek(Now()) IS 1 then simply checks to see whether it is Sunday. If it is Sunday, the condition evaluates to TRUE; if not, it evaluates to FALSE.

If the condition is TRUE, the text between the <cfif> and </cfif> tags is displayed. It's as simple as that.

Multi-condition If Statements

A couple of problems exist with the code in Listing 9.1, the most important of which is that weekends include both Sundays and Saturdays. Therefore, the code to check whether it is the weekend needs to check for both days.

Here is a revised version of the code (see Listing 9.2); save this file as if2.cfm, and then execute it.

TIP

So as not to have to retype all the code as you make changes, use Dreamweaver's File, Save As menu option to save the file with the new name, and then edit the newly saved file.


Listing 9.2. if2.cfm
 <!--- Name: if2.cfm Author: Ben Forta (ben@forta.com) Description: Demonstrate use of multiple conditions Created: 12/1/2004 ---> <html> <head>  <title>If 2</title> </head> <body> <!--- Is it the weekend? ---> <cfif (DayOfWeek(Now()) IS 1) OR (DayOfWeek(Now()) IS 7)>  <!--- Yes it is, great! --->  It is the weekend, yeah! </cfif> </body> </html> 

The code is the same as Listing 9.1, except for the <cfif> statement itself:

 <cfif (DayOfWeek(Now()) IS 1) OR (DayOfWeek(Now()) IS 7)> 

This statement contains two conditions, one that checks whether the day of the week is 1 (Sunday), and one that checks whether it is 7 (Saturday). If it is Sunday or Saturday, the message is displayed correctly. Problem solved.

To tell ColdFusion to test for either condition, the OR operator is used. By using OR if either of the specified conditions is TRUE, the condition returns TRUE. FALSE is returned only if neither condition is TRUE. This is in contrast to the AND operator, which requires that both conditions be trUE and returns FALSE if only one or no conditions are trUE. Look at the following code snippet:

 <cfif (FirstName IS "Ben") AND (LastName IS "Forta")> 

For this condition to be TRUE, the FirstName must be Ben and the LastName must be Forta. Ben with any other LastName or Forta with any other FirstName fails the test.

AND and OR are logical operators (sometimes called Boolean operators). These two are the most frequently used logical operators, but others are supported, too, as listed in Table 9.2.

Table 9.2. CFML Logical Operators

OPERATOR

DESCRIPTION

AND

Returns trUE only if both conditions are trUE

OR

Returns TRUE if at least one condition is TRUE

XOR

Returns trUE if either condition is trUE, but not if both or neither are trUE

EQV

Tests for equivalence and returns trUE if both conditions are the same (either both TRUE or both FALSE, but not if one is TRUE and one is FALSE)

IMP

Tests for implication; returns FALSE only when the first condition is TRUE and the second is FALSE

NOT

Negates any other logical operator


TIP

You probably noticed that when multiple conditions (either AND or OR) were used, each condition was enclosed within parentheses. This is not required but is generally good practice. Not only does it make the code cleaner and easier to read, but it also prevents bugs from being introduced by expressions being evaluated in ways other than you expected. For example, if both AND and OR are used in a condition, AND is always evaluated before OR, which might or might not be what you want. Parentheses are evaluated before AND, so by using parentheses you can explicitly manage the order of evaluation.


If and Else

The code in Listing 9.2 is logically correct: If it is Sunday or Saturday, then it is indeed the weekend, and the weekend message is displayed. But what if it is not Sunday or Saturday? Right now, nothing is displayed at all; so let's fix that.

Listing 9.3 contains the revised code, capable of displaying a non-weekend message if necessary (see Figure 9.2). Save this code as if3.cfm, and then execute it.

Listing 9.3. if3.cfm
 <!--- Name: if3.cfm Author: Ben Forta (ben@forta.com) Description: Demonstrate use of <cfif> and <cfelse> Created: 12/1/2004 ---> <html> <head>  <title>If 3</title> </head> <body> <!--- Is it the weekend? ---> <cfif (DayOfWeek(Now()) IS 1) OR (DayOfWeek(Now()) IS 7)>  <!--- Yes it is, great! --->  It is the weekend, yeah! <cfelse>  <!--- No it is not :-( --->  No, it's not the weekend yet, sorry! </cfif> </body> </html> 

Figure 9.2. <cfelse> enables the creation of code to be executed when a <cfif> test fails.


The only real difference between Listings 9.2 and 9.3 is the introduction of a new tag<cfelse>. <cfif> is used to define code to be executed when a condition is trUE, and <cfelse> defines code to be executed when a condition is FALSE. <cfelse> takes no attributes and can be used only between <cfif> and </cfif> tags. The new code will now display It is the weekend, yeah! if it is Sunday or Saturday and No, it's not the weekend yet, sorry! if not. Much better.

But before you move on, Listing 9.4 contains one more refinementa cleaner <cfif> statement. Save Listing 9.4 as if4.cfm, and then execute it (it should do exactly what Listing 9.3 did).

Listing 9.4. if4.cfm
 <!--- Name: if4.cfm Author: Ben Forta (ben@forta.com) Description: Demonstrate saving <cfif> results Created: 12/1/2004 ---> <html> <head>  <title>If 4</title> </head> <body> <!--- Is it the weekend? ---> <cfset weekend=(DayOfWeek(Now()) IS 1) OR (DayOfWeek(Now()) IS 7)> <!--- Let the user know ---> <cfif weekend>  <!--- Yes it is, great! --->  It is the weekend, yeah! <cfelse>  <!--- No it is not :-( --->  No, it's not the weekend yet, sorry! </cfif> </body> </html> 

The more complex conditions become, the harder they are to read, so many developers prefer to save the results of executed conditions to variables for later use. Look at this line of code (from Listing 9.4):

 <cfset weekend=(DayOfWeek(Now()) IS 1) OR (DayOfWeek(Now()) IS 7)> 

Here, <cfset> is used to create a variable named weekend. The value stored in this variable is whatever the condition returns. So, if it is a weekend (Sunday or Saturday), weekend will be TRUE, and if it is not a weekend then weekend will be FALSE.

See Chapter 8, "Using ColdFusion," for detailed coverage of the <cfset> tag.


The <cfset> statement could be broken down further if required, like this:

 <!--- Get day of week ---> <cfset dow=DayOfWeek(Now())> <!--- Is it the weekend? ---> <cfset weekend=(dow IS 1) OR (dow IS 7)> 

The end result is the same, but this code is more readable.

After weekend is set, it can be used in the <cfif> statement:

 <cfif weekend> 

If weekend is TRUE, the first block of text is displayed; otherwise, the <cfelse> text is displayed.

But what is weekend being compared to? In every condition thus far, you have used an operator (such as IS) to test a condition. Here, however, no operator is used. So what is weekend being tested against?

Actually, weekend is indeed being tested; it is being compared to TRUE. Within a <cfif> the comparison is optional, and if it's omitted, a comparison to TRUE is assumed. So, <cfif weekend> is functionally the same as

 <cfif weekend IS TRUE> 

The weekend variable contains either trUE or FALSE. If it's trUE, the condition is effectively

 <cfif TRUE IS TRUE> 

which obviously evaluates to TRUE. But if weekend is FALSE, the condition is

 <cfif FALSE IS TRUE> 

which obviously is FALSE.

I said that weekend contained either TRUE or FALSE, but you should feel free to test that for yourself. If you add the following line to your code, you'll be able to display the contents of weekend:

 <cfoutput>#weekend#</cfoutput> 

As you can see, you have a lot of flexibility when it comes to writing <cfif> statements.

Multiple If Statements

There's one more feature of <cfif> that you need to look atsupport for multiple independent conditions (as opposed to one condition made up of multiple conditions).

The best way to explain this is with an example. In the previous listings you displayed a message on weekends. But what if you wanted to display different messages on Sunday and Saturday? You could create multiple <cfif> </cfif> blocks, but there is a better way.

Listing 9.5 contains yet another version of the code; this time the filename should be if5.cfm.

Listing 9.5. if5.cfm
 <!--- Name: if5.cfm Author: Ben Forta (ben@forta.com) Description: Demonstrate <cfelseif> use Created: 12/1/2004 ---> <html> <head>  <title>If 5</title> </head> <body> <!--- Get day of week ---> <cfset dow=DayOfWeek(Now())> <!--- Let the user know ---> <cfif dow IS 1>  <!--- It's Sunday --->  It is the weekend! But make the most of it, tomorrow it's back to work. <cfelseif dow IS 7>  <!--- It's Saturday --->  It is the weekend! And even better, tomorrow is the weekend too! <cfelse>  <!--- No it is not :-( --->  No, it's not the weekend yet, sorry! </cfif> </body> </html> 

Let's take a look at the previous code. A <cfset> is used to create a variable named dow, which contains the day of the week (the value returned by DayOfWeek(Now()), a number from 1 to 7).

The <cfif> statement checks to see whether dow is 1, and if trUE, displays the Sunday message (see Figure 9.3). Then a <cfelseif> is used to provide an alternative <cfif> statement:

 <cfelseif dow IS 7> 

Figure 9.3. If dow is 1, the Sunday message is displayed.


The <cfelseif> checks to see whether dow is 7, and if TRUE, displays the Saturday message (see Figure 9.4). Finally, <cfelse> is used to display text if neither the <cfif> nor the <cfelseif> are TRUE.

Figure 9.4. If dow is 7, the Saturday message is displayed.


<cfelseif> is essentially a combined <cfelse> and <cfif>, hence its name.

Saving conditions' results to variables, as you did here with the dow variable and previously with weekend, instead of repeating code makes your code more readable. But it also has another benefit. If you use the exact same expressions (getting the day of the week, say) in multiple places, you run the risk that one day you'll update the code and not make all the changes in all the required locations. If just a single expression must be changed, that potential problem is avoided.

No limit exists to the number of <cfelseif> statements you use within a <cfif> tag, but you can never use more than one <cfif> or <cfelse>.

NOTE

Use of <cfelseif> and <cfelse> are optional. However, if <cfelse> is used, it must always be the last tag before the </cfif>.


Putting It All Together

<cfif> is one of the most frequently used tags in CFML. So before we move on to the next subject, let's walk through one more examplea slightly more complex one.

Guess the Number is a simple game: I'm thinking of a number between 1 and 10; guess what number I am thinking of. ColdFusion selects a random number, you guess a number, and ColdFusion will tell you whether you guessed the correct one.

Listing 9.6 contains the code for guess1.cfm. Save it in the 9 directory, but don't execute it from within Dreamweaver. Instead, use this URL to execute it:

 http://localhost:8500/ows/9/guess1.cfm?guess=n 

Replace n with a number from 1 to 10. For example, if you guess 5, use this URL:

 http://localhost:8500/ows/9/guess1.cfm?guess=5 

You must pass the guess URL parameter, or an error will be thrown. When you pass that parameter you'll see an output similar to the ones shown in Figures 9.5 and 9.6. (Actually, if you reload the page often enough, you'll see both figures.)

Listing 9.6. guess1.cfm
 <!--- Name: guess1.cfm Author: Ben Forta (ben@forta.com) Description: if statement demonstration Created: 12/1/2004 ---> <html> <head>  <title>guess the number - 1</title> </head> <body> <!--- Pick a random number ---> <cfset RandomNumber=RandRange(1, 10)> <!--- Check if matched ---> <cfif RandomNumber IS URL.guess>  <!--- It matched --->  <cfoutput>  You got it, I picked #RandomNumber#! Good job!  </cfoutput> <cfelse>  <!--- No match --->  <cfoutput>  Sorry, I picked #RandomNumber#! Try again!  </cfoutput> </cfif> </body> </html> 

Figure 9.5. URL.guess matched the number ColdFusion picked.


Figure 9.6. URL.guess did not match the number ColdFusion picked.


The first thing the code does is pick a random number. To do this, the RandRange() function is used. RandRange() takes two parameters (the range) and returns a random number within that range. The following line of code thus returns a random number from 1 to 10 (inclusive) and saves it in a variable named RandomNumber:

 <cfset RandomNumber=RandRange(1, 10)> 

Next, the randomly generated number is compared to the guessed number (which was passed as a URL parameter) using the following <cfif> statement:

 <cfif RandomNumber IS URL.guess> 

URL.guess is the variable containing the guess value provided in the URL. If the two match, the first message is displayed; if they don't, the second message is displayed.

URL variables and their use are covered in detail in Chapter 10, "Creating Data-Driven Pages." For now, its sufficient to know that variables passed as parameters to a URL are accessible via the URL scope.


But what if no guess parameter was specified? You will recall from Chapter 8 that referring to a variable that doesn't exist generates an error. Therefore, you should modify the code to check that URL.guess exists before using it. Listing 9.7 contains the modified version of the code; save this file as guess2.cfm.

NOTE

This is why I said not to try guess1.cfm from within Dreamweaver. If you had, the code would have been executed without allowing you to pass the necessary URL parameter, and an error would have been generated.


Listing 9.7. guess2.cfm
 <!--- Name: guess2.cfm Author: Ben Forta (ben@forta.com) Description: if statement demonstration Created: 12/1/2004 ---> <html> <head>  <title>Guess the Number - 2</title> </head> <body> <!--- Pick a random number ---> <cfset RandomNumber=RandRange(1, 10)> <!--- Check if number was passed ---> <cfif IsDefined("URL.guess")>  <!--- Yes it was, did it match? --->  <cfif RandomNumber IS URL.guess>  <!--- It matched --->  <cfoutput>  You got it, I picked #RandomNumber#! Good job!  </cfoutput>  <cfelse>  <!--- No match --->  <cfoutput>  Sorry, I picked #RandomNumber#! Try again!  </cfoutput>  </cfif> <cfelse>  <!--- No guess specified, give instructions --->  You did not guess a number.<BR>  To guess a number, reload this page adding  <B>?guess=n</B> (where n is the guess, for  example, ?guess=5). Number should be between  1 and 10. </cfif> </body> </html> 

Listing 9.7 introduces a new concept in <cfif> statementsnested <cfif> tags (one set of <cfif> tags within another). Let's take a look at the code. The first <cfif> statement is

 <cfif IsDefined("URL.guess")> 

IsDefined() is a CFML function that checks whether a variable exists. IsDefined("URL.guess") returns trUE if guess was passed on the URL and FALSE if not. Using this function, you can process the guess only if it actually exists. So the entire code block (complete with <cfif> and <cfelse> tags) is within the TRUE block of the outer <cfif>, and the original <cfif> block is now nestedit's a <cfif> within a <cfif>.

This also enables you to add another <cfelse> block, on the outer <cfif>. Remember, the outer <cfif> checks whether URL.guess exists, so <cfelse> can be used to display a message if it doesn't. Therefore, not only will the code no longer generate an error if guess was not specified, it will also provide help and instruct the user appropriately (see Figure 9.7).

Figure 9.7. By checking for the existence of expected variables, your applications can provide assistance and instructions if necessary.


NOTE

The code in Listing 9.7 clearly demonstrates the value of indenting your code. The code within each <cfif> block is indented, and the deeper the nesting, the further the indentation. This type of formatting is extremely popular among professional developers because it makes finding matching (or mismatched) code blocks much easier.


As a rule, nesting should be avoided unless absolutely necessary. And nesting really isn't necessary in this game. Listing 9.8 takes the game code one step further, this time using <cfelseif> and multiple clause conditions to create tighter (and better performing) code. Save Listing 9.8 as guess3.cfm.

Listing 9.8. guess3.cfm
 <!--- Name: guess3.cfm Author: Ben Forta (ben@forta.com) Description: if statement demonstration Created: 12/1/2004 ---> <html> <head>  <title>Guess the Number - 3</title> </head> <body> <!--- Pick a random number ---> <cfset RandomNumber=RandRange(1, 10)> <!--- Check if number was passed ---> <cfif IsDefined("URL.guess")       AND (RandomNumber IS URL.guess)>  <!--- It matched --->  <cfoutput>  You got it, I picked #RandomNumber#! Good job!  </cfoutput> <cfelseif IsDefined("URL.guess")           AND (RandomNumber IS NOT URL.guess)>  <!--- Did not match --->  <cfoutput>  Sorry, I picked #RandomNumber#! Try again!  </cfoutput> <cfelse>  <!--- No guess specified, give instructions --->  You did not guess a number.<BR>  To guess a number, reload this page adding  <B>?guess=n</B> (where n is the guess, for  example, ?guess=5). Number should be between  1 and 10. </cfif> </body> </html> 

Again, the code starts with the random number generation. Then this <cfif> statement is used:

 <cfif IsDefined("URL.guess")       AND (RandomNumber IS URL.guess)> 

As explained earlier, AND requires that both conditions be trUE. Therefore, the first message is displayed only if URL.guess exists and if the numbers match. The second condition is in a <cfelseif> statement:

 <cfelseif IsDefined("URL.guess")           AND (RandomNumber IS NOT URL.guess)> 

Here too, IsDefined() is used to check that URL.guess exists. The second condition is trUE only when the numbers don't match, in which case the second message is displayed.

NOTE

Notice that the <cfif> and <cfelseif> statements in listing 9.8 are split over two lines. ColdFusion ignores white space (including line breaks), so code can be spread over as many lines as needed, and shorter lines of code (as used here) can be easier to read.


The <cfelse> here is evaluated only if <cfif> and <cfelseif> are both not evaluated, in which case it would be clear that URL.guess was not defined.

The same result occurs, but this time without nesting.

CAUTION

As a rule, don't nest unless you really have to. Although nesting is legal within your code, nested code tends to be easier to make mistakes in, harder to debug, and slower to execute.


Take a look at this line of code again:

 <cfif IsDefined("URL.guess")       AND (RandomNumber IS URL.guess)> 

You might be wondering why an error would not be generated if URL.guess did not exist. After all, if the IsDefined() returns FALSE, shouldn't the next condition cause an error because URL.guess is being referred to?

The answer is no, because ColdFusion supports short-circuit evaluation. This means that conditions that don't affect a result are never evaluated. In an AND condition, if the first condition returns FALSE, then the result will always be FALSE, regardless of whether the second condition returns TRUE or FALSE. Similarly, in an OR condition, if the first condition is TRUE, the result will always be trUE, regardless of whether the second condition is trUE or FALSE. With short-circuit evaluation, conditions that don't affect the final result aren't executed, to save processing time. So in the previous example, if IsDefined("URL.guess") returns FALSE, RandomNumber IS URL.guess is never even evaluated.

Let's finish this game application with one last revision. Listing 9.9 should be saved as file guess4.cfm.

Listing 9.9. guess4.cfm
 <!--- Name: guess4.cfm Author: Ben Forta (ben@forta.com) Description: if statement demonstration Created: 12/1/2004 ---> <html> <head>  <title>Guess the Number - 4</title> </head> <body> <!--- Set range ---> <cfset GuessLow=1> <cfset GuessHigh=10> <!--- Pick a random number ---> <cfset RandomNumber=RandRange(GuessLow, GuessHigh)> <!--- Was a guess specified? ---> <cfset HaveGuess=IsDefined("URL.guess")> <!--- If specified, did it match? ---> <cfset Match=(HaveGuess)        AND (RandomNumber IS URL.guess)> <!--- Feedback ---> <cfoutput> <cfif Match>  <!--- It matched --->  You got it, I picked #RandomNumber#! Good job! <cfelseif HaveGuess>  <!--- Did not match --->  Sorry, I picked #RandomNumber#! Try again! <cfelse>  <!--- No guess specified, give instructions --->  You did not guess a number.<BR>  To guess a number, reload this page adding  <B>?guess=n</B> (where n is the guess, for  example, ?guess=5). Number should be between  #GuessLow# and #GuessHigh#. </cfif> </cfoutput> </body> </html> 

Quite a few changes were made in Listing 9.9. First, the range high and low values are now variables, defined as follows:

 <!--- Set range ---> <cfset GuessLow=1> <cfset GuessHigh=10> 

By saving these to variables, changing the range (perhaps to allow numbers 120) will be easier. These variables are passed to the RandRange() function and are used in the final output (when instructions are given if no guess was specified) so that the allowed range is included in the instructions.

Next, the simple assignment <cfset HaveGuess=IsDefined("URL.guess")> sets variable HaveGuess to either TRUE (if guess was specified) or FALSE. The next assignment sets a variable named Match to trUE if the numbers match (and guess was specified) or to FALSE. In other words, two simple <cfset> statements contain all the necessary intelligence and decision making, and because the results are saved to variables, using this information is very easy indeed.

This makes the display code much cleaner. <cfif Match> displays the first message if the correct guess was provided. <cfelseif HaveGuess> is executed only if the <cfif> failed, which must mean the guess was wrong. In addition, the <cfelse> displays the instructions (with the correct range included automatically).

It doesn't get much cleaner than that.

NOTE

Listing 9.9 demonstrates a coding practice whereby logic (or intelligence) and presentation are separated. This is a practice that should be adopted whenever possible, as the resulting code will be both cleaner and more reusable.


Switch Statements

All the conditional processing used thus far has involved <cfif> statements. But as I stated at the beginning of this chapter, ColdFusion also supports another form of conditional processing: switch statements.

The best way to understand switch statements is to see them used. Listing 9.10 should be saved as file switch.cfm.

When you have executed Listing 9.10, you'll notice that it does exactly what Listing 9.5 (file if5.cfm) does. The code here is very different, however.

Listing 9.10. switch.cfm
 <!--- Name: switch.cfm Author: Ben Forta (ben@forta.com) Description: Demonstrate use of <cfswitch> and <cfcase> Created: 12/1/2004 ---> <html> <head>  <title>Switch</title> </head> <body> <!--- Get day of week ---> <cfset dow=DayOfWeek(Now())> <!--- Let the user know ---> <cfswitch expression="#dow#">  <!--- Is it Sunday? --->  <cfcase value="1">  It is the weekend! But make the most of it, tomorrow it's back to work.  </cfcase>  <!--- Is it Saturday? --->  <cfcase value="7">  It is the weekend! And even better, tomorrow is the weekend too!  </cfcase>  <!--- If code reaches here it's not the weekend --->  <cfdefaultcase>  No, it's not the weekend yet, sorry!  </cfdefaultcase> </cfswitch> </body> </html> 

First the day of the week is saved to variable dow (as it was earlier), but that variable is then passed to a <cfswitch> statement:

 <cfswitch expression="#dow#"> 

<cfswitch> takes an expression to evaluate; here, the value in dow is used. The expression is a string, so number signs are needed around dow. Otherwise, the text dow will be evaluated instead of the value of that variable.

<cfswitch> statements include <cfcase> statements, which each match a specific value that expression could return. The first <cfcase> is executed if expression is 1 (Sunday) because 1 is specified as the value in <cfcase value="1">. Similarly, the second <cfcase> is executed if expression is 7 (Saturday). Whichever <cfcase> matches the expression is the one that is processed, and in this example, the text between the <cfcase> and </cfcase> tags is displayed.

If no <cfcase> matches the expression, the optional <cfdefaultcase> block is executed. <cfdefaultcase> is similar to <cfelse> in a <cfif> statement.

As I said, the end result is exactly the same as in the example using <cfif>. So, why would you use <cfswitch> over <cfif>? For two reasons:

  • <cfswitch> usually executes more quickly than <cfif>.

  • <cfswitch> code tends to be neater and more manageable.

You can't always use <cfswitch>, however. Unlike <cfif>, <cfswitch> can be used only if all conditions are checking against the same expression. In other words when the conditions are all the same, and only the values being compared against differ. If you need to check a set of entirely different conditions, <cfswitch> would not be an option, which is why you couldn't use it in the game example.

TIP

Although the example here uses <cfswitch> to display text, that is not all this tag can do. In fact, just about any code you can imagine can be placed between <cfcase> and </cfcase>.

<cfcase> tags are evaluated in order, so it makes sense to place the values that you expect to match more often before those that will match much less often. Doing so can improve application performance slightly because ColdFusion won't have to evaluate values unnecessarily.

This is also true of sets of <cfif> and <cfelseif> statements: Conditions that are expected to match more frequently should be moved higher up the list.




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