Menu

As simple as possible, as complex as necessary

Simpler optional cfarguments

15 June 2011

Following John Maeda's First Law of Simplicity I'm always on the look out for ways in which I can thoughtfully reduce the amount of code in my apps.

Raymond Camden recently listed a number of cases where ColdFusion developers often write more code than necessary. I haven't been guilty of any of those particular "mistakes" for some years now, but a comment by Peter Boughton drew my attention to an area where I have been writing more than I need.

<cffunction name="makeCatPurr" returntype="string" output="false">
	<cfargument name="cat" type="Cat" required="true">
	<cfargument name="loudness" type="numeric" required="false" default="1">
	<cfreturn arguments.cat.purr( loudness=arguments.loudness )>
</cffunction>

I've been completely ignoring that fact that by default all function arguments are optional, so required="false" should never be needed. cfscript enforces this economy since the way to make an argument optional is to simply leave off the required keyword in the signature. Here's the Cat component where the loudness argument is also optional.

<cfcomponent displayname="Cat">
<cfscript>	
	function init()
	{
		return this;
	}
	
	function purr( numeric loudness=1 )
	{
		return "<p style=""font-size:#arguments.loudness#em"">Purrr</p>";
	}
</cfscript>
</cfcomponent>

Illogical

The interesting point Peter was making is that if you specify a default value then the argument will be optional even if you set required="true". Of course doing so would be illogical since required arguments by definition require a value and so never need a default, but it's worth bearing in mind ColdFusion's order of precedence. If you want an argument to be required, make sure you don't specify a default - accidentally or otherwise.

<cffunction name="makeCatPurr" returntype="string" output="false">
	<cfargument name="cat" type="Cat" required="true">
	<cfargument name="loudness" type="numeric" required="true" default="1">
	<cfreturn arguments.cat.purr( loudness=arguments.loudness )>
</cffunction>

<cfdump var="#makeCatPurr#">

Even though I've set the loudness argument to be required and it is shown as such in the dumped meta-data below, the presence of the default means CF will not complain if it's missed out.

<cfoutput>
#makeCatPurr( New Cat() )#
</cfoutput>
screenshot of function metadata showing that the loudness argument is required, but no exception is thrown when it is missing

Posted on . Updated

Comments

  • Formatting comments: See this list of formatting tags you can use in your comments.
  • Want to paste code? Enclose within <pre><code> tags for syntax higlighting and better formatting and if possible use script. If your code includes "self-closing" tags, such as <cfargument>, you must add an explicit closing tag, otherwise it is likely to be mangled by the Disqus parser.
Back to the top