Switch/Case statement constants

Posted on Tuesday, November 2nd, 2010 at 9:58 pm

This is more of a note than anything else concerning an error that throws when trying to run a switch case against a variable. Before analyzing this I want to simply display a function that illustrates a working switch statement, and then the same switch statement replacing the case value with a variable. Let’s take a look.

Working switch statement

public boolean function dynamicSwitch()
{
	var data1 = "matthew";
	var data2 = "cook";

	var expression = data1;

	switch(expression)
	{
		case "matthew":
		{
			return true;
		}

		default:
		{
			return false;
		}
	}
}

Throws an error

public boolean function dynamicSwitch()
{
	var data1 = "matthew";
	var data2 = "cook";

	var expression = data1;

	switch(expression)
	{
		case data1:
		{
			return true;
		}

		default:
		{
			return false;
		}
	}
}

So the second example uses the variable ‘data1′ as the value for the case. This throws a Coldfusion error indicating that case values must be constants (a hard-coded value). This makes sense, and maybe you’re wondering why a variable would ever need to be used for the case value. Admittedly, it certainly makes no sense in the above example, but I do personally like to declare all component constants at the top of my component by storing them in a ‘constant’ namespace and prefixing the variable name with a ‘c_’. Coldfusion doesn’t literally support constant variables, so having some rules around how to syntactically declare constant variables in Coldfusion makes sense to me.

So in my case I had set some constant variables in my component, and in a function needed to compare a passed in argument against them. It was a scenario where the value either would or would not equal the value of one of my constants. Hard-coding those values again for a switch statement would have been plain old bad practice. Nonetheless, it was also in this scenario that I learned I could not use a variable for my case value.

The result was that I used an if-else statement instead. It works fine. The switch statement would have been more appropriate, but take what you can get I guess.

Tags
CategoryColdfusion

Leave a Reply

*
(Won't be published) *