coldfusionparameter-passingcffunction

Handling optional arguments: CFArgument versus isDefined


I have a question about cfargument. If I am sending a parameter when calling a .cfc, is there any benefit to defining it as argument first?

<cffunction name="someFunction" ....>
    <cfargument name="myArg" required="no">

Or can I just use IsDefined() inside the function, without defining an argument?

<cffunction name="someFunction" ....>
   ...
   <cfif isDefined("arguments.myArg")>
      do something
   </cfif>

I tried them and know that they both work. However, what is a difference between defining the argument and using isDefined()? Can that affect efficiency?


Solution

  • It's not about efficiency, it's about documentation. Here's an exceprt from my company's coding standards document on cfargument.

    When using the CFARGUMENT tag in a ColdFusion function, the following attributes are required:

    ColdFusion does not require that you use cfargument tags but they provide validation (type safety) and act as additional documentation, therefore always provide a cfargument tag for each named argument your function expects.

    Rules:

    1. The name of an argument does not have to be prefixed with a data type (avoid Hungarian Notation).
    2. Always specify the type attribute in your cfargument tags. Try to avoid using type="any".
    3. If an argument is required, specify required="true" but do not specify a defaultattribute value.
    4. If an argument is not required, specify required="false" and specify a default attribute value.
    5. If you need to detect whether a non-required argument was provided, do not specify default, but instead use structKeyExists(arguments,"ARGNAME") in the function body (remember that when you specify default, you cannot tell the difference between the caller omitting that argument and the caller providing that same default value as an argument).
    6. When referring to a variable passed into a function as an argument, ALWAYS reference the arguments scope. (Don't reference foo, reference arguments.foo.)
    7. Do not manipulate the value of an argument passed into a function. CF passes some variable data types by reference and any manipulation done within a function alters the value of the variable at the level from which it was called. Copy the arguments struct to a function local variable using duplicate() to avoid conflicts, then manipulate the function local variable as needed.
    8. Do not add keys to the arguments struct that were not originally passed into the function. Adding new keys can make debugging very difficult. Instead, copy the arguments struct to a new function local variable using duplicate to avoid conflicts and add new keys to that struct.

    HTH