Does This Method Exist?


In one of our applications, we have a couple of “core views”, i.e. view stuff that is used in a couple different places, so we have it in one tidy CFM for easier maintenance. For most of them, the content coming in is the same or similar in nature, however we have one where they are not quite the same. With our registration view, the populating object (a “bean”) could be a “real” registration object, with a full set of methods, or it could be a “pending” registration object, which has a slightly smaller set of methods.

When we first built the view, it wasn't really an issue because the methods that only a real registration would have were also only called on when certain flags were in place, which were never set for a pending registration. Then we added a new bit to the view, which isn't limited by the flags, whether or not it was a “transferred” registration. This caused us to start getting system errors when trying to view a pending object using this view. We could have just made yet another flag, but I figured there had to be a way to just say “hey, if you don't have the method getPreviousRegistration, skip this bit”.

Well, we have IsDefined, but that just got us an error that the method wasn't found (well duh, that's why I asked you!). I could just wrap it in a try/catch, but then I'd have to deal with trying to filter out this fake error from real ones, and that really doesn't match how I like to code. So I Google'd around for “ColdFusion function exists”. To my surprise, I found almost nothing, beyond a very brief thread on Adobe (2 posts) with an “answer” that lacked any details.

The brief answer did give me a starting point, though, so I decided to expand on it here in case anyone else finds themselves wondering hwo to do it. Basically, you can do this using a combination of StructFindValue and getMetaData. StructKeyExists doesn't work, at least the way I solved this, because the function names in getMetaData aren't set as keys, but rather values. So the resulting bit that went into my CFIF?

ArrayLen(StructFindValue(getMetaData(bRegistration), "getPreviousRegistration")) GT 0

If the function is there, you'll have a populated there. If it isn't, you'll have an empty array. It may not be the most “elegant” of solutions with the multiple nested functions, but it works and it is working well. So if anyone else wants to test for a function's existence, here is one way to do it. If you can think of some others, by all means share so that next time someone Google's the question, they get some hits! 😉

Update 4/17/13 @ 7:45 am: Thanks to Aaron who showed me how StructKeyExists can work in this case, if you skip all the MetaData stuff.  So now we have a cleaner bit of code:

StructKeyExists(bRegistration, "getPreviousRegistration")

I didn't even think to try it cause I was stuck on the idea that “it's an object”, forgetting that often for ColdFusion, they can be treated similarly 🙂