Search code examples
delphisyntaxconstructorrecord

Can record constructors make record constants more concise?


I have some tabular data:

Foo       Bar
-------------
fooes     42
bars      666 
...

So, I declare the entity structure:

type TFoo = record
  Foo: string;
  Bar: Integer
end;

and the table of entities:

const FOOES = array [M..N] of TFoo = (
  // Have to specify the field names for each record...
  (Foo: 'fooes'; Bar:  42),
  (Foo: 'bars';  Bar: 666)
  { so on }
);

As you see, this looks quite verbose and redundant, and it is because I initialize all of the fields for all of the records. And there is a lot of editing if I copy tabular data prepared elsewhere. I'd prefer to not enumerate all of the fields and stick to the more laconic C style, that is, constants only. And here comes the record constructor...

Can record constructors help me in this case?

Here's an example in C. You'll notice that we don't have to specify the field names in each declaration:

#include <stdio.h>

typedef struct {
        char    foo[10];
        int     bar;
} foo;

int main(void) {
        /* Look here */
        foo FOOES[2] = {{"foo", 42}, {"bar", 666}};
        int i = 0;
        for (; i < 2; i++) {
                printf("%s\t%d\n", FOOES[i].foo, FOOES[i].bar);
        }
        return 0;
}

Solution

  • If you want it done in source then what you have already typed is your answer. You could, of course, put the data in separate arrays and initialize them that way, but that can make your code look messy.

    You could also store them in an text file (Foo=Bar format) and read them into a TStringList at run-time (SL.LoadFromFile()). But even with a sorted TStringList it will be far less efficient (MyVariable := SL.Values['Foo1']; for example).

    There are a million ways to solve this problem outside of source code. Taking it from the other direction, put the data into Excel and create an Excel macro to build the source and put it into the clipboard to paste into your PAS file. This wouldn't be too difficult and probably easier than formatting the Delphi code within the IDE.