Archive for April 2, 2016

Smart Pascal and the Buddha object

April 2, 2016 2 comments

I’m not sure how to introduce the full implications of this topic. It greatly depends on your background with curly languages (C#, C++, Java) and your love for all things Delphi, FreePascal, Oxygene and Smart Mobile.

But stick with me, it will be fun!

The buddha object

In traditional object pascal all classes must inherit from TObject right? No matter what you do you just could not escape that fact. Unless you used records, defined functions as fields and mapped the entry points manually. Which we sometimes have to do when talking to old-school C libraries or esoteric kernel code, but that’s another matter. TObject is the mother of all classes, thats the general rule (or was).

But what if someone took the time to completely re-design this from scratch. I mean the whole inheritance system inside the compiler? What if we got rid of TObject as the ultimate ancestor and instead introduced a “self-less” object? Kind of like a Buddha object? One that can become anything?

Live prototypes

Our chief compiler engineer, Eric Grange, is nothing short of a wizard when it comes to these things. So a while back he introduced exactly what I described above. So now we get to do super cool tricks that C#, Java and JavaScript have been doing for a while.

Passing self-less classes as parameters and calling back into it!

Passing self-less classes as parameters and calling back into it!

So what just happened above? Well, when the user clicks a button (w3button5 in this case), we call the method “ProcedureToCall”. But wait! We pass as the parameter a class! A class of no specific type, which requires no initiation (no constructor).

But notice how we set a new value (UnKnown.NewValue) which was not in the original declaration. And after that, we call back into the ghost object and dump the “this” property.

Without getting to technical, “this” means the same as “self”. But since this is an anonymous ghost class, it has no self — so “this” then refers to the current context. Now let’s look at what the output is when we dump the object to console:


Its all there, even the new property

Pretty cool huh? Now let’s look at the code generated for these procedures. I think you will agree it’s both readable and straight forward:

That's almost a 1:1 code generation!

That’s almost a 1:1 code generation!

Mind: Blown!

If you don’t quite get why this is important and powerful, then think about what this does for talking with external libraries, refactoring older code, and most importantly – constructing objects in real-time by code. Once you start playing around with this I think you will agree — it’s the bomb!

Now ponder why W3Button5 has a “self” parameter 😉