The Dopefly Tech Blog

<< The Dopefly Tech Blog Main page

Fun with Functions and CFCs II - Object Hacking, There Is No Privacy

posted under category: ColdFusion on December 11, 2007 at 1:00 am by MrNate

There are a lot of fun and interesting things you can do with ColdFusion components that languages like Java just don't let you. This is part 2 in my series to explore the interesting things that you can do with ColdFusion components and functions.

Before we begin, let's make a test CFC - here's the one I'm using; Test.cfc:

  <cffunction name="init" access="public">
    <cfreturn this />

  <cffunction name="privateMethod" access="private">
    <cfreturn "This is a Private Method!" />

  <cffunction name="publicMethod" access="public">
    <cfreturn "This is a Public Method!" />


Now we'll make an instance of it in a plain-jane .cfm file:
<cfset myCFC = createObject("component","Test").init()>

Now here comes the fun part. I want to get and execute the private method from the .cfm page. Not allowed, right? Not exactly. let's make a free-floating function in my .cfm file (this could be done with a cffunction tag, but I like the familiar script syntax):
  function getCurrentVariables() {return variables;}

If I call getCurrentVariables() now, it will return the current document's variables scope, which consists of a reference to that function and to my CFC instance's this scope, but what if I put that function onto my test CFC's public interface?

<cfset myCFC.getVariables = getCurrentVariables />

now, myCFC.getVariables() gives me the variables scope of the CFC! if I dump myCFC.getVariables(), I can see everything that's going on inside. Woah, now I can play with the internals all I want.

#myCFC.getVariables().privateMethod()# returns "This is a Private Method!"

Too old to comment!
On Dec 11, 2007 at 1:00 AM Ian ( said:
Doesn't that violate some encapsulation practices? It's neat that you can do it but why would you want to?

On Dec 11, 2007 at 1:00 AM Robert Gatti ( said:
Ian, there are a lot of things like this that CF allows you to do. Most of which, you are correct, violate the inner most sanctum of OO principals. The benefit, however, is allowing fast easy dynamic programming. Frameworks that want to be truly separate from code could inject all required setup/config functions to anything (cfc or struct) you tell it should be a controller. Debug and test suits can get all data needed to figure out why that variable is not being set. But when it comes right now to it, just because a language like ColdFusion, Ruby, Perl, Smalltalk, Lisp allows you to do something, just because you have the easy ability to manipulate inner workings doesn't mean you should.
Too old to comment!