Search code examples
delphioopclassrecorddelphi-2006

When should I use enhanced record types in Delphi instead of classes?


Delphi 2006 introduced new capabilities for records, making them more 'object-oriented'.

In which situations is the record type more appropriate for a design than a class type? Which advantage does it have to use these record types?


Solution

  • You have records, objects and classes.

    Records are available since turbo pascal 1. They are lightweight, capable of having properties and methods, but they do not support inheritance, There are some issues with functions that return records. If these records have methods this sometimes gives internal errors:

    type
      TRec = record 
        function Method1: Integer;
      end;
    
    function Func: TRec;
    
    
    procedure Test;
    var
      x : TRec;
    
    begin
      Func.Method1; // Sometimes crashes the compiler
      // Circumvention:
      x := Func;
      x.Method1; // Works
    end;
    

    Objects are introduced with turbo pascal 5 if I'm correct. They then provided a way for OO with pascal. They are more or less deprecated with the introduction of Delphi, but you can still use them. Objects can implement interfaces.

    Classes are introduced with Delphi 1 and the most versatile. They implement interfaces and support inheritance. But each class variable is a hidden pointer. This means that classes need to be created on the heap. Luckily this process is mostly hidden.

    Below is a table with the differences between the three. I added the interface for completion.

                      |Class|Object|Record|Interface|
    ------------------|-----------------------------|
    Are pointers?     |  y  |  n   |  n   |    y    |
    Inheritance       |  y  |  y   |  n   |    y    |
    Helpers           |  y  |  n   |  y   |    n    |
    Impl. Interface   |  y  |  y   |  n   |    -    |
    Visibility        |  y  |  y   |  n   |    n    |
    Method            |  y  |  y   |  y   |    y    |
    Fields            |  y  |  y   |  y   |    n    | 
    Properties        |  y  |  y   |  y   |    y    |
    Consts            |  y  |  y   |  y   |    n    |
    Types             |  y  |  y   |  y   |    n    |
    Variants          |  n  |  n   |  y   |    n    |
    Virtual           |  y  |  n   |  y   |    -    |
    ------------------|-----------------------------|