The Dopefly Tech Blog

« The Dopefly Tech Blog Main page

Fun with Functions and CFCs VII - Dynamic interfaces and better duck-typing

posted under category: ColdFusion on December 18, 2007 at 1:00 am by Nathan

I actually found another good use for all this fun I've been having with CF's dynamic nature.

What if you want a component to implement another interface when your application is running? What if you are trying to do duck typing and want to make sure your component really is what it is supposed to be?

In my previous post about mixin methods, I touched on a method of mixing an entire component into another, essentially merging the two. This is great for a lot of reasons.

For duck typing, if you're attempting to pass one type of object into another, no matter what type of object it is, just so long as it has the required functions, this is both a way to make one object quack like that other object, and to validate that it should quack alike.

If you are keeping a typed system and you want to pass one type of object into a system that is expecting another, you can make an object of that type, inject the current state and methods into that object and return that object in place of the other. Wow, yeah, I can't actually imagine doing that, but it's great that it's possible.

Robin Hillard had the same idea, but in reverse (and also 3 years ago), where you pass your component to the component you want to duck/quack/emulate. This makes more sense actually, that way you don't have to cheat and introspect the private variables scope, it's available, but all Robin's methods are only set on the public scope of the original object. But it's six or half a dozen.

Even still, this isn't the best way. Joe Rinehart came to the same conclusion I do (but almost 2 years ago), and that is to use ColdSpring to set your CFC via mixin method. He makes some good points, too, and it is a solid sounding solution.

(jump break)


One thing Joe brings to light is the thought of what a mixin consists of. Is it just functions, or does it include properties (public or private)? I would argue both, but that one mixin should never overwrite anything in the resulting (aka more important, aka duck typing, not the duck typed) object. Joe thinks it should be just the functions.

Here's a bad idea! Go typeless, then mix all your components together into one super-everything beast. Mix in your DAOs with your services, with your business objects. Wow. it can do everything. Then you only have one object in memory. Yeah, no idea why you would do that either. BTW, watch out for identical methods that do different things. Maybe it would be nice if you have a handful of service objects, like a UserService, a PreferencesService, etc., you can mix those types all together, then you would have a single, unified service layer.

Yeah, still not a good idea, but I could almost envision doing that.

But not quite.