Tuesday, May 31, 2011

ORM Entities and isStruct

I was writing a function today and ran into something that through me off. I have a function that can take either an object (ORM) or a struct. Inside the function I needed to check of the value was a struct or an object to determine how to access the properties / keys. This seem like a simple thing to do so I wrote the following:
public void function foo(required any bar) {
  if(isStruct(arguments.bar)) {
    ...do something
  } else {
    ...do something similar
  }
}
And this worked just fine when the argument is a struct. However, when I tested it with the ORM entity it failed inside the struct block of the if statement. This didn't seem right, so I went and checked the documentation for the isStruct method and here is the explanation I found:

Returns True, if is a ColdFusion structure or is a Java object that implements the java.lang.Map interface.

So if the function will only return true if it is a ColdFusion structure or object that implements java.lang.Map, why would it return true for my ORM entity? I posted the finding on the cf-orm-dev google group, and it turns out that all ColdFusion components will return true for isStruct. Thanks to Brian Kotek for pointing out that it wasn't just my ORM entities that behaved this way. So either ColdFusion components are ColdFusion structs or it at some point implements the java.lang.Map interface.

I still find this to be a little strange, so I did some tests to see if components really were structs.
obj = createObject('component');
obj.key1 = 'value1';
obj['key2'] = 'value2';
StructInsert(obj,'key3','value3');
As it turns out, all three of these forms worked. So, I guess ColdFusion components are structs or can at least be manipulated in some ways the same.

Luckily, my original problem is easily solved. The isObject method returns false for structs and true for components, so all I had to do was reverse my cases and use the isObject method.

Still I'd be interested if anyone had a deeper understanding of why components behave like structs.

1 comment:

  1. I have always thought of components as structures of functions. Each "key" is a function and the "data" is the code for the function. Structures are a fundamental building block in ColdFusion so it seems natural to me that components are implemented that way, but that is only my opinion.

    ReplyDelete