Menu

As simple as possible, as complex as necessary

The simplicity of ColdFusion 9 Part 2

30 March 2011

Continuing my list of ColdFusion 9 enhancements which can help you write less code...

New way of creating objects

To instantiate a ColdFusion Component (object) pre-CF9, I would have used CreateObject():

ID = 1;
user = CreateObject( "component","model.User" ).init( ID );

This can now be shortened to:

ID = 1;
user = New model.User( ID );

The new keyword will automatically call and return the component's init method (if it exists) passing it the arguments you specify.

If the path needs to be dynamic (i.e. it depends on a variable), then just surround it in quotes:

ID = 1;
modelVersion = "20081213";
user = New "model.#modelVersion#.User"( ID );>

Abbreviating at the cost of clarity should be avoided, but this is not only shorter, but more "English-like" and therefore clearer.

Application-wide datasource

Since early in my CF career I've followed good practice in abstracting the name of the application datasource to a global variable, such as application.dsn, that can be referenced whenever running a query.

<cfquery name="q" datasource="#application.dsn#" username="#application.dsnUser#" password="#application.dsnPassword#">
	SELECT ID FROM posts
</cfquery>

With CF9.0 came the ability to specify the datasource name in Application.cfc...

this.datasource = "blog";

...and the CF9.0.1 updater belatedly let you specify a login:

this.datasource	=	{
	name="blog"
	,username="coldfusion"
	,password="letmein"
};

Which leads to a delightful de-cluttering of our cfquery tags.

<cfquery name="q">
	SELECT ID FROM posts
</cfquery>

<cfquery>
	DELETE FROM posts WHERE ....
</cfquery>

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