Home > Articles > Programming > General Programming/Other Languages

This chapter is from the book

This chapter is from the book

Records

Records are a technique for binding together multiple data types into a single structure. Examples of using records can be found in the RecordWorks program found in the Chap03 directory of your accompanying CD.

Consider the following method:

procedure TForm1.Button1Click(Sender: TObject);
var
  FirstName: String;
  LastName: String;
  Address: String;
  City: String;
  State: String;
  Zip: String;
begin
  FirstName := `Blaise';
  LastName := `Pascal';
  Address := `1623 Geometry Lane';
  City := `Clemont';
  State := `CA';
  Zip := `81662'
end;

The String declarations in the var section are all part of an address. Here is how you can bind these identifiers into one record:

procedure TForm1.Button2Click(Sender: TObject);
type
  TAddress = record
    FirstName: String;
    LastName: String;
    Address: String;
    City: String;
    State: String;
    Zip: String;
  end;
var
  Address: TAddress;
begin
  Address.FirstName := `Blaise';
  Address.LastName := `Pascal';
  Address.Address := `1623 Geometry Lane';
  Address.City := `Clemont';
  Address.State := `CA';
  Address.Zip := `81662'
end;

In this second example, a record declaration has been added to the type section of the Button2Click method. A variable of type TAddress has been declared in the var section. Dot notation is used in the body of the Button2Click method to enable you to reference each field of the record: Address.FirstName. People often will read out loud such a declaration as "Address dot FirstName," hence the term dot notation.

C/C++ NOTE

A record in Object Pascal is the same thing as a struct in C/C++. However, in C/C++, the line between a struct and an object is blurred, while in Object Pascal they are two distinctly different types. Pascal records do not support the concept of a method, although you can have a pointer to a method or function as a member of a record. However, that pointer references a routine outside the record itself. A method, on the other hand, is a member of an object.

Records and with Statements

You can create a with statement to avoid the necessity of using dot notation to reference the fields of your record. Consider the following code fragment:

procedure TForm1.Button3Click(Sender: TObject);
type
  TPerson = Record
    Age: Integer;
    Name: String;
  end;
var
  Person: TPerson;
begin
  with Person do begin
    Age := 100046;
    Name := `ET';
  end;
end;

The line with Person do begin is a with statement that tells the compiler that the identifiers Age and Name belong to the TPerson record. In effect, with statements offer a kind of shorthand to make it easier to use records or objects.

NOTE

with statements are a double-edged sword. If used properly, they can help you write cleaner code that's easier to understand. If used improperly, they can help you write code that not even you can understand. Frankly, I tend to avoid the syntax because it can be so confusing. In particular, the with syntax can break the connection between a record or object and the fields of that record or object.

For instance, you have to use a bit of reasoning to realize that Age belongs to the TPerson record and is not, for instance, simply a globally scoped variable of type Integer. In this case, the true state of affairs is clear enough, but in longer, more complex programs, it can be hard to see what has happened. A good rule of thumb might be to use with statements if they help you write clean code and then to avoid them if you are simply trying to save time by cutting down on the number of keystrokes you type.

Variant Records

A variant record in Pascal enables you to assign different field types to the same area of memory in a record. In other words, one particular location in a record could be either of type A or of type B. This can be useful in either/or cases, where a record can have either one field or the other field, but not both. For instance, consider an office in which you track employees either by their name or by an ID, but never by both at the same time. Here is a way to capture that idea in a variant record:

procedure TForm1.VariantButtonClick(Sender: TObject);
type
  TMyVariantRecord = record
    OfficeID: Integer;
    case PersonalID: Integer of
      0: (Name: ShortString);
      1: (NumericID: Integer);
  end;
var
  TomRecord, JaneRecord: TMyVariantRecord;
begin
  TomRecord.Name := `Sammy';
  JaneRecord.NumericID := 42;
end;

The first field in this record, OfficeID, is just a normal field of the record. I've placed it there just so you can see that a variant record can contain not only a variant part, but also as many normal fields as you want.

The second part of the record, beginning with the word case, is the variant part. In this particular record, the PersonalID can be either a String or an Integer, but not both. To show how this works, I declare two records of type TMyVariantRecord and then use the Name part of one variant record and the NumericID of the other record instance.

Name and NumericID share the same block of memory in a TVariantRecord—or, more precisely, they both start at the same offset in the record. Needless to say, a String takes up more memory than an Integer. In any one instance of the record at any one point in time, you can have either the String or the Integer, but not both. Assigning a value to one or the other field, will, at least in principle, overwrite the memory in the other field.

The compiler will always allocate enough memory to hold the largest possible record that you can declare. For instance, in this case, it will always allocate 4 bytes for the field OfficeID and then 256 bytes for the String, giving you a total of 260 bytes for the record. This is the case even if you use only the OfficeID and NumericID fields, which take up only 8 bytes of memory.

For me, the most confusing part of variant records is the line that contains the word case. This syntax exists to give you a means of telling whether the record uses the NumericID or the Name field. Listing 3.4 shows a second example that focuses on how to use the case part of a variant record.

Listing 3.4  The case Part of a Variant Record Used in the ShowRecordType Method

unit Main;

interface

uses
  Windows, Messages, SysUtils,
  Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls;

type
  TMyVariantRecord = record
    OfficeID: Integer;
    case PersonalID: Integer of
      0: (Name: ShortString);
      1: (NumericID: Integer);
  end;

  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    procedure ShowRecordType(R: TMyVariantRecord);
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.ShowRecordType(R: TMyVariantRecord);
begin
  case R.PersonalID of
    0: ShowMessage(`Uses Name field: ` + R.Name);
    1: ShowMessage(`Uses NumericID: ` + IntToStr(R.NumericID));
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Sam, Sue: TMyVariantRecord;
begin
  Sam.OfficeID := 1;
  Sue.PersonalID := 0;
  Sue.Name := `Sue';
  ShowRecordType(Sue);
  Sam.OfficeID := 2;
  Sam.PersonalID := 1;
  Sam.NumericID := 1;
  ShowRecordType(Sam);
end;

end.

In this example, the two records are passed into the ShowRecordType method. One record has the PersonalID set to 0; the other has it set to 1. ShowRecordType uses this information to sort out whether any one particular record uses the Name field or the RecordID field:

  case R.PersonalID of
    0: ShowMessage(`Uses Name field: ` + R.Name);
    1: ShowMessage(`Uses NumericID: ` + IntToStr(R.NumericID));
  end;

As you can see, if PersonalID is set to 0, the Name field is valid; if it is set to 1, the NumericID field is valid.

NOTE

A case statement plays the same role in Object Pascal that switch statements play in C/C++ and Java. Other than the obvious syntactical similarities, there is no significant connection between the case part of a variant record and case statements. In and of themselves, case statements have nothing to do with variant records. It is simply coincidence that, in this example, case statements are the best way to sort out the two different types of records that can be passed to the ShowRecordType procedure. The following code, however, would also get the job done:

procedure TForm1.ShowRecordType2(R: TMyVariantRecord);
begin
  if R.PersonalID = 0 then
    ShowMessage(`Uses Name field: ` + R.Name)
  else
    ShowMessage(`Uses NumericID: ` + IntToStr(R.NumericID));
end;

Here is one last variant record that shows how far you can press this paradigm:

procedure TForm1.HonkerButtonClick(Sender: TObject);
type
  TAnimalType = (atCat, atDog, atPerson);
  TFurType = (ftWiry, ftSoft);
  TMoodType = (mtAggressive, mtCloying, mtGoodNatured);
  TAnimalRecord = record
    Name: String;
    Age: Integer;
    case AnimalType: TAnimalType of
      atCat: (Talk: ShortString;
            Fight: ShortString;
            Food: ShortString);
      atDog: (Fur: TFurType;
            Description: ShortString;
            Mood: TMoodType);
      atPerson:(Rank: ShortString;
             SerialNumber: ShortString);
  end;

var
  Cat, Dog, Person: TAnimalRecord;
begin
  Cat.Name := `Valentine';
  Cat.Age := 14;
  Cat.Talk := `Meow';
  Cat.Fight := `Scratch';
  Cat.Food := `Cheese';
  Dog.Name := `Rover';
  Dog.Age := 2;
  Dog.AnimalType := atDog;
  Dog.Fur := ftWiry;
  Dog.Description := `Barks';
  Dog.Mood := mtGoodNatured;
end;

In this example, I declare an enumerated type named TAnimalType. I use this type in the case part of the variant record, which enables me to use descriptive names rather than numbers for each case:

  TAnimalType = (atCat, atDog, atPerson);
  TAnimalRecord = record
    case AnimalType: TAnimalType of
      atCat:
      atDog:
      atPerson:
  end;

The other important bit of code in this example is the fact that you can place multiple fields in each element of the case part:

atDog: (Fur: TFurType;
        Description: ShortString;
        Mood: TMoodType);

Here you can see that the atDog part of the variant records has three separate fields: Fur, Description, and Mood.

NOTE

I use ShortStrings in these examples because you cannot use the system-allocated variables of type AnsiStrings, WideStrings, dynamic arrays, or Interfaces in a variant record. However, you can use pointers to these forbidden types.

Variant records don't play a large role in Object Pascal programming. However, they are used from time to time in some fairly crucial places, and they fit nicely into our search for the more advanced parts of the language that might not be obvious at first glance to a newcomer. In fact, I've seen many experienced Pascal programmers get tripped up by this syntactically complex entity.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020