Elliott's Blog | Life Through Math, Algorithms and Code

Mar/10

24

Using Prototypal Inheritance in ColdFusion

Ben Nadel was recently looking at Prototypal Inheritance in ColdFusion, which is incidentally one of the topics I talk about in my I bet you didn’t know you could do that with ColdFusion presentation, which I gave at BFusion 2008 and will be doing an updated version of at CFUnited 2010. </shameless-plug>

The code samples have a Prototype.cfc and some examples that use complete objects as the prototype like with JS.

user = createObject("component","User").init();
admin = createObject("component","Admin").init();
admin.setPrototype(user);

me = admin.new();
me.setName("Elliott Sprehn");

// Somewhere off in plugin land...
function toXML() {
	return "
		
			#this.getName()#
		";
}
user.toXML = toXML;

// In the application's code
writeOutput( me.toXML() );
/*
	
		Elliott Sprehn
	
*/

One reason I really like this is that it lets you arbitrarily extend the model in plugins without impacting object creation performance.

There’s a tendency to go crazy with the Factory pattern and then broadcast lots of events (transfer takes this approach with actionAfterNewTransferEvent and friends). Unfortunately it makes object creation slower and slower since each create has to notify more and more listeners.

The Eclipse IDE ran into this problem and called it the “event storm” where a single mouse click might fire thousands of events and make the whole IDE seem slow.

Using prototypal inheritance we can pre-compute the entire prototype chain and all the complex object state so that each object create only needs one extra setPrototype().

Thinking outside the traditional class based object approach can solve many future problems and make your life easier. Whether it be by using function pointers creatively or something even less conventional like prototypal inheritance.

No tags

2 comments

  • Ben Nadel · March 24, 2010 at 10:47 pm

    Awesome – I’ll definitely be catching your preso at CFUnited. Your presentations tend to blow my mind :)

    Reply

  • Matt Gersting · August 3, 2010 at 11:11 am

    Hey Elliott – pleasure meeting you at CFUNITED this year. I was wondering – would it be possible for you to post the updated version of the “Bet You Didn’t Know” presentation and sample code? I’m particularly interested in the updated Prototype.cfc!

    Reply

Leave a Reply

<<

>>

Theme Design by devolux.nh2.me