A Magical Gathering – Part 1

Sometimes combining different programming techniques reveals the hidden beauty of a programming language.

A few years ago I was able to create such a thing with some older and newer language features. The outcome revealed some kind of magic that really amazed myself.

The recipe is pretty simple: take an enumerator, mix it with a class helper and pour it over an invokeable custom variant.

A what?

Forget it for the moment and let’s start at the beginning.

The idea was to iterate over a dataset in an easy way avoiding that tedious writing like:

I had something more elegant in mind, something like:

As TDataSet lacks an enumerator I decided to write one by myself. No problem with that one, only a few things to implement. My first approach looked like this:

At that time I found it a brilliant idea to have the current record index as the iteration variable.

Now how to squeeze that enumerator into the dataset? Class helpers came to the rescue:

With that I was able to write my dataset loop as:

So the first step was done by combining an enumerator with a class helper.

And what have we gained now? We reduced the original code by just two lines for the cost of adding a new variable yielding an overall of one line profit (if we don’t count for the var that probably has been there before). We have to write quite a couple of loops to outweigh the enumerator and class helper code, do we?

What bothered me most was that the body of the loop remained unchanged. All that referencing of the record fields with

was still cluttered all over the code. I felt like I just missed the point.

I just had not reached my target and the longer part of the way still laid ahead. But more on that in the second part…

About Uwe Raabe

Addicted to Pascal/Delphi since the late 70's
This entry was posted in Delphi, Programming. Bookmark the permalink.

One Response to A Magical Gathering – Part 1

  1. GunSmoker says:

    A very nice (almost) first post! 😀 The second one is also pretty cool.

Comments are closed.