CFCs vs. UDFs

Ben Forta recently blogged about a conversation he had with Simon Horwith in London about when to use a CFC versus when to use a custom tag. I completely agree with the conclusion they came to, which was basically that CFCs make sense for logic and data abstraction, and Custom Tags primarily make sense for presentation.

Another interesting question to ask is when should one use CFCs versus UDFs? While I would much rather have this conversation at a Starbucks in London, I guess my weblog will have to suffice.

Since the release of CFMX, I actually find myself writing very few UDFs. I still find them occasionally useful for “one-off” application-specific functionality, but in general, I’m much more inclined to write a component for the following reasons:

  • State: Components can contain state while UDFs cannot. For instance, many native ColdFusion functions require you to pass in the data being operated on in addition to parameters to configure the operation. Having a stateful data structure can promote better encapsulations, make your code cleaner, and in general, be more convenient. Even if your function appears as though it should be static, why not put it in a component and allow yourself some flexibility to expand the functionality in the future?
  • Logical Grouping: I like to be able to put related functions together in a single component rather than just create a bunch of basically unrelated functions. For instance, one could imagine a single date component with 41 different functions as opposed to 41 date-related functions among a total of 235 unrelated functions.
  • Organization: I like having the ability to organize my components into packages. Although you can organize your UDFs into directories, packages provide additional benefits and flexibility.
  • Inheritance: I honestly don’t use a ton of inheritance with ColdFusion components, but I do use it occasionally, and I think my application architecture benefits from it. Although UDFs can certainly invoke each other to achieve the “code reuse” aspect of inheritance, in general, inheritance allows for far more sophisticated modeling.

So how do you decide when to use a component versus a UDF? And who’s up for rewriting all 235 native ColdFusion functions, grouping them into components, and organizing them into packages?