functioncoldfusionoptional-arguments

Passing optional arguments to a function (where they are also optional)


Background

I am experiencing a problem when I attempt to pass optional arguments to another function. The function being called also has optional arguments so I'm trying to get that optionality to propagate all the way through.

The problem I'm experiencing is that since cold fusion doesn't have a concept of null (or at least not really) when an optional argument is omitted it literally doesn't exist.

component accessors=true output=false persistent=false {
    public void function foo(String otherOptional, String optional1,String optional2 ){

        //Other code
        //Other code
        //Other code
        bar(optional1=optional1,optional2=optional2);

    }

    public void function bar(String optional1, String optional2 ){
         //Other code
    }
}

For example in the above code if foo is called without any arguments I receive an error

Variable OPTIONAL1 is undefined.

The error occurred in D:/web/experimental/OptionalTest.cfc: line 11
9 : 
10 :        //Other code
11 :        bar(optional1=optional1,optional2=optional2);
12 : 
13 :    }

Question

Is there a way to pass optional arguments to another function where they are also optional without causing errors?

Solutions I've considered are:


Solution

  • Here's a solution that involves StructKeyExists but probably in a way that's different from what you've already considered:

    bar(
      optional1 = StructKeyExists(arguments, 'optional1') ? arguments.optional1 : JavaCast('null', 0),
      optional2 = StructKeyExists(arguments, 'optional2') ? arguments.optional2 : JavaCast('null', 0)
    );