The amazing adventures of Doug Hughes

Cfreturn Exits Methods

I recently blogged about a minor bug in the Alagad Image Component which left files locked. A reader suggested I talk more about it. The problem, in a nutshell, is that code placed after cfreturn in cffunctions will not execute.

As a rather contrived example, let’s say you want to create a method that will add two numbers, return the value, and call another method with the total. Your method might look like this:

<cffunction name="addEmUp" access="public" output="false">
 <cfargument name="num1" required="yes" type="numeric" />
 <cfargument name="num2" required="yes" type="numeric" />

 <!--- add the attrubutes and store in total --->
 <cfset var total = arguments.num1 + arguments.num2 />

 <!--- return the sum --->
 <cfreturn total />

 <!--- call another method and pass in total --->
 <cfset someOtherMethod(total) />
 </cffunction>

However, the someOtherMethod method will never be called. This is because the cfreturn tag returns the value of total and exits the method. In general, you should typically have your cfreturn tag as the last line in a function. So, the code above would look like this:

<cffunction name="addEmUp" access="public" output="false">
 <cfargument name="num1" required="yes" type="numeric" />
 <cfargument name="num2" required="yes" type="numeric" />

 <!--- add the attrubutes and store in total --->
 <cfset var total = arguments.num1 + arguments.num2 />

 <!--- call another method and pass in total --->
 <cfset someOtherMethod(total) />

 <!--- return the sum --->
 <cfreturn total />
 </cffunction>

There are, of course, uses for having cfreturn in various places in your method. For instance, you might have various paths though the method all of which need to return data at different points. You could place a cfreturn at the end of each of these paths. However, I prefer to create a variable to hold the value to return. Then, my last line of code returns that value.

In the end, to fix the bug in the Image Component, all I needed to do was make my cfreturn the last line of code in the problem method.

Comments on: "Cfreturn Exits Methods" (1)

  1. Scott Barnes said:

    CFRETURN can also be used when code-debuging cfincludes.

    Say you have a CFINCLUDE thats got something amiss inside it, and you know that the first 10 lines are good, but it goes south from their on out. A good way to do the line by line test, is to use cfreturn instead of cfabort. This will actually break out of the CFINCLUDE and return to its parent context (ie the page that did the cfinclude itself)

    Its also an alternative to CFABORT in some cases.

    Like

Comments are closed.

Tag Cloud

<span>%d</span> bloggers like this: