Passing arguments into a ColdFusion method

Filed under: ColdFusion

comments (2) Views: 5,360

It seems that many beginning ColdFusion programmers are confused by the range of means by which arguments can be passed into a ColdFusion method. So here's a quick post to explain the various ways which can be used, and why you might select one over another.

First, a list of the types of usages

  • Specific placement: where the arguments must be in the position in which they're defined in the method.
  • Named arguments: where arguments can be passed into a method in any arrangement you like
  • Argument collection: where arguments are passed into a method included as as structure containing keys the same name as that of the required arguments.

Specific placement is the simplest. You examine a methods signature, and provide the arguments in the proper order.


methodName('noelle',42)

The upside is that it's very literal. Examine the documentation and it's plain to see which arguments are which. The drawback is that if you have a method which takes more than 4 or 5 arguments it can be tough to figure out what's what.

Next up is named arguments. With named arguments, the values can be placed in any order you wish.


methodName(name='noelle',id=42)

The benefit is that the developer can choose which order to put their arguments in. The downside is that it's extra code. This primarly used to self-document code.

Finally we have argumentCollection. This method is powerful, and offers a lot of flexibility to the developer. You simply create a structure containing all of the appropriate required arguments to your method, then pass in that structure as an argumentCollection.


myStruct.name='noelle';
myStruct.id=42
methodName(argumentCollection=myStruct)

One of the primary benefits to using this method is being able to conditionally pass in whatever arguments are needed for your specific usage. If you need to conditionalize the name value, it can be done using standard cfif, or cfscript, conditional logic, like so:


if ((2 + 2) EQ 5) {
	myStruct.name='noelle';
} else {
	myStruct.name='evan';
}
myStruct.id=42
methodName(argumentCollection=myStruct)

Lastly, argumentCollection method can also be used for CF tags as well.


<cfset myStruct.enableCFoutputOnly='yes'>
<cfset myStruct.requestTimeOut='20'>
<cfset myStruct.enableCFoutputOnly='yes'>
<cfsetting argumentCollection="#myStruct#">

Amazon logo

If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!

comments powered by Disqus