Using in-built function names for your methods

December 24, 2009

James Buckingham mentioned on Twitter that he wanted to use IsValid as a method name in an application he is working on but ColdFusion won't let you as it already has a built-in method named IsValid. Ben Nadel has also blogged about this a while back in his post Overriding Built-In ColdFusion Methods With Custom ColdFusion Component Methods.

Well, this is now only partly true as in ColdFusion 9 you can have method names that are the same as ColdFusion in-built functions.

For example, this code will work on ColdFusion 9, but not on ColdFusion 8.

Test.cfc


<cfcomponent output="false">
<cffunction name="init" output="false" returntype="any">
<cfreturn this>
</cffunction>
<cffunction name="IsValid" output="false" returntype="boolean">
<cfreturn true>
</cffunction>
</cfcomponent>

index.cfm


<cfset Test = CreateObject("component", "Test").init()>

<cfdump var="#Test.IsValid()#">

However, it should be noted that it only works because you are specifying the scope before calling the IsValid method. If you try to do this it will still throw an error.

Test.cfc


<cfcomponent output="false">
<cffunction name="init" output="false" returntype="any">
<cfset var foo = IsValid()>
<cfreturn this>
</cffunction>
<cffunction name="IsValid" output="false" returntype="boolean">
<cfreturn true>
</cffunction>
</cfcomponent>

If you really want to call the IsValid method name from inside the component you can prefix the "this" scope, although this isn't really considered best practice and you could only call IsValid if the method was public.

 


2 comments

  1. Interesting, I hadn't thought about it from this perspective.

    As you point out, though, using the same name as a built in function should be avoided. There is always another appropriate method name.


    DW

    Comment by Dan Wilson – December 24, 2009
  2. Hey Dan, when I found this out I did think of upgrade issues when future version of CF come out, which may include new functions named the same as existing methods in your code. For example I know that the new throw() function has broken quite a few sites. At least in the future (if the methods are called externally) future CF server versions won't stop the site working.

    Comment by John Whish – December 26, 2009

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.