Wednesday, March 2, 2011

Making your source code with arrays easier to read

If your source code include references to arrays, it maybe better to refer to items in those arrays using pre-defined constant variable names rather than plain old numbers. Let's take the following code for example, which basically sets up fields of a database table:

Fields[ 0 ].AsString  := 'Joe Blow';
Fields[ 1 ].AsInteger := 25;
Fields[ 3 ].AsString  := 'Hiking';
Listing #1 : Delphi code. Download initaray (0.2 KB).
Of course, unless you know which fields are at which array position, it could make it harder to maintain above code. Let's replace those numbers with constant names:
  // TC = Table Clients (clients.dbf) for example
  TC_AGE      = 1;
  TC_HOBBIES  = 3;

// ... other code ...

Fields[ TC_FULLNAME ].AsString  := 'Joe Blow';
Fields[ TC_AGE      ].AsInteger := 25;
Fields[ TC_HOBBIES  ].AsString  := 'Hiking';
Listing #2 : Delphi code. Download cnstaray (0.31 KB).
The extra time it would take to create those constant names will most likely be paid off when you have to modify your source code in the future, specially if someone else has to maintain your code.

Twitter Delicious Facebook Digg Stumbleupon Favorites More

Design by Kang Iwan K-sev | Thank's for your visit To My Site - Ridwan Mulyana | Cibeureum