Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Coldfusion define type of array in function argument?

Tags:

coldfusion

Inside a ColdFusion component I declare a function like this:

string function render(required Array actions) output=false {
//...
}

So the function parameter can only accept an Array. However, I need to make sure the array contains only "ActionItem" objects (there is an ActionItem.cfc component)

Is there a way in ColdFusion to type-hint the array contents? What solution do you suggest in this case?

like image 955
Philipp Avatar asked Dec 21 '22 02:12

Philipp


2 Answers

In short, as Peter has said in his comment, the basic answer is "you can't". ColdFusion doesn't have the notion of typeful arrays.

There's two ways around this. Firstly the brute-force approach of validating each array item as you need it, making sure it's the type you need. This is what Peter suggests, and generally what I'd do.

Failing that you could implement an ActionItemCollection.cfc which itself contains an array of ActionItems, and leave it to ActionItemCollection.cfc to only accept ActionItem objects, so by the time your render() function receives its ActionItemCollection argument, it "knows" each element in the collection is definitely an ActionItem.

That said, that's perhaps an awful lot of work when you could just get render() to check if the element is legit, and throw an exception if not. It's not a perfect solution, but CF is creating an imperfect situation, so fair enough.

like image 172
Adam Cameron Avatar answered Feb 11 '23 17:02

Adam Cameron


To elaborate on my comment, the following is an outline of a possible collection you could create.

I love collection classes and the ArrayCollection class here is very reusable and allows you to use the wrapped array as an object.

    component ArrayCollection()
    {

        public function init()
        {
            variables.collection = [];

            return this;
        }

        public any function get();

        public function set(required array collection);

        public function add(required any item);

        public function remove();

    }

    component ActionItemCollection extends ArrayCollection
    {
        public function add(required ActionItem item);

        public ActionItem function get();
    }


    component otherComponnet{

        public string function render(required ActionItemCollection actions) 
        {

        }

    }

It my be overkill in some circumstances, however it allows you to enfore the type of items within the array!

like image 42
AlexP Avatar answered Feb 11 '23 15:02

AlexP