Delphi: Operator Overloading

Delphi has the ability to include operator overloading for structured types, this allows you to use any standard operator on your structured type. The Delphi documentation on the subject states that you can apply operator overloading to both structured types and classes, however this is wrong, it can only be applied to structured types. Here’s an example of it being used:

program OperatorsTest;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TIntValue = record
  private
    FValue: Integer;
  public
    class operator Add(const a, b: TIntValue): TIntValue;
    class operator Implicit(const a: Integer): TIntValue;
    class operator Implicit(const a: TIntValue): Integer;
    property Value: Integer read FValue;
  end;

{ TIntValue }

class operator TIntValue.Add(const a, b: TIntValue): TIntValue;
begin
  Result.FValue := a.FValue + b.FValue;
end;

class operator TIntValue.Implicit(const a: Integer): TIntValue;
begin
  Result.FValue := a;
end;

class operator TIntValue.Implicit(const a: TIntValue): Integer;
begin
  Result := a.FValue;
end;

var
  Int: TIntValue;

begin
  Int := 5;
  Int := Int + 10;
  WriteLn(IntToStr(Int));
  Readln; // Prevent window from closing
end.

The documentation shows you all of the operators you can overload and has some extra examples as well.

Read More

Delphi: Singleton Patterns

I’m a big fan of singleton patterns, basically a singleton pattern lets a class maintain a single instance of itself which you can then reuse as often as you want without having to create a new instance. This is achieved by creating a private static field inside the class that can hold an instance of itself, when the user wants to retrieve the instance for the first time, a new one is created and stored in the field, if there’s already one present, the class will return that instance. The implementation I usually use also has automated cleaning of the instance once the application terminates by adding a shared constructor. It’s also possible to add a private constructor to the class to disable the coder to create any instances of it directly without using the singleton pattern or subclassing it.

Here’s an example of the singleton pattern with cleaning:

type
  TTestClass = class
  private
    class var FInstance: TTestClass;
  public                               
    class function GetInstance: TTestClass;
    class destructor DestroyClass;
  end;

{ TTestClass }

class destructor TTestClass.DestroyClass;
begin
  if Assigned(FInstance) then
    FInstance.Free;
end;

class function TTestClass.GetInstance: TTestClass;
begin
  if not Assigned(FInstance) then
    FInstance := TTestClass.Create;
  Result := FInstance;
end;

It’s also possible to add a property named Instance or something even shorter that will get the instance from the GetInstance method which you would then make private, this will shorten the amount of code you have to write when using it.

Read More

Delphi: Static Members

Delphi comes with support for both OOP and procedural code, something you come across less every day as more languages move over to an OOP-only structure. Because of this static code in Delphi is often added as procedural code, which makes sense of course. However, Delphi also has the ability to add static members to classes which can be quite useful at times.

Delphi features several different kinds of static members. The first are fields and properties. A Delphi class can contain any number of static fields and properties which work the exact same way as a regular member would, however they can only be accessed in a static context. Same as with regular properties a static property can retrieve values by calling methods, however all of these accessors and mutators have to be static members as well.

Aside from fields, properties and methods, Delphi classes can also hold shared constructors/destructors. A shared constructor is called when the application is started and allows you to initialize static fields or other stuff you might want to initialize from a static context in or possibly outside of the class. A shared destructor is called when your application is terminated, this allows you to clean up static resources and such. This is similar to the initialization and finalization clauses, but part of a class instead of the entire unit.

Static fields have to be added by adding the keywords “class var” as prefix. For properties you just add “class”. Static methods need to have prefix “class” and they can also take a “static;” at the end, this isn’t required for regular methods, but it is for mutators and accessors. Shared constructors/destructors also only need to have “class” added in front of them. Note that static contructors/destructors can take any name, even Create/Destroy, but i personally prefer the names CreateClass/DestroyClass.

Here’s an example that will show you all of these features:

program StaticTest;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

type
  TTestClass = class
  private
    class var FStaticField: TStrings;
    class function GetStaticField: string; static;
    class procedure SetStaticField(const Value: string); static;
  public
    class property StaticField: string read GetStaticField write SetStaticField;
    class constructor CreateClass;
    class destructor DestroyClass;
  end;

{ TTestClass }

class constructor TTestClass.CreateClass;
begin
  FStaticField := TStringList.Create;
  FStaticField.Text := 'Hello world!';
end;

class destructor TTestClass.DestroyClass;
begin
  FStaticField.Free;
end;

class function TTestClass.GetStaticField: string;
begin
  Result := FStaticField.Text;
end;

class procedure TTestClass.SetStaticField(const Value: string);
begin
  FStaticField.Text := Value;
end;

begin
  WriteLn(TTestClass.StaticField);
  ReadLn; // Stop window from closing
end.

Read More

Cross-platform Delphi

After doing some further investigation it seems that the cross-platform support for Delphi has yet again been moved up to a next release. The fact that Embarcadero wants to wait for them to fully stabilize the product before releasing it is certainly an admirable thing to do, but it does bring up some questions…

So what does this mean for RAD Studio XE? We’ve seen 2 previews so far, it shows us some nice new features, a lot of integrations of 3rd party applications to make coding more convenient. However, a lot of these applications are limited because they have a paying version, yet there’s barely any or no details on how this is dealt with in RAD Studio. Another somewhat big concern is whether this release is actually worth purchasing when updating from RAD Studio 2010. So far we have seen no actual new Delphi language features being previewed, all that remains is a bunch of new tools in the IDE of which now part only seem to be added to somewhat bulk up the product and make it appear as more than just a bugfix release. Personally I’m waiting for some details on language features, however i must admit that the addition of RadPHP makes the product somewhat more appealing as it had to be purchased separately previously and since the initial release as Delphi for PHP, RadPHP seems to have matured quite a lot.

It seems Embarcadero has also released a new roadmap, though there’s very little communication from the company about why the cross-platform support was moved up or even that it was, it clearly shows on the new roadmap that was released just 6 days ago. The cross-platform support has been jumping around a lot on the roadmap since it was initially announced, but it seems they have now finally brought everything together in a release named project “Pulsar”, which I assume will be Delphi 2012. The release promises to include x64 support for windows applications and the inclusion of cross-platform compiling for 32-bit mac applications, only for Delphi however. The release has no mentioning of Linux support which previously vanished from the roadmap, however it has reappeared in the Wheelhouse release, however note that they carefully refer to the Linux support as support for Linux servers which might suggest it will not support GUI applications. This release will also bring the cross-platform and x64 support to the other RAD Studio products, mainly C++ Builder of course.

It seems to be clear Embarcadero wants to have the product catching up with competing products with the Commodore release, which will feature full 32- and 64-bit support for all platforms. However, when counting the number of projects it would suggest this being part of Delphi 2014. Even though they are certainly making an effort, it seems Embarcadero is once again dropping the ball here as they are already losing many (potential) customers because they do not support 64-bit and cross-platform at the present time, certainly 64-bit support will also become more pressing in the future as gradually more and more platforms are moving over to 64-bit. Will there be a market left for them when they finally catch up with the current day products of their competitors in 3 years from now?

An interesting item that I’m coming across a few times on the roadmap is the considered addition of a cross-platform VCL library. Originally this item was part of the roadmap as a somewhat standard item included with cross-platform support. However it seems that currently they are only considering to add this. How will this affect the cross-platform support? As I mentioned before they are saying that they will only include Linux server support into the Wheelhouse release, that would certainly require no GUI, so a cross-platform VCL library would not be required. However, for the Mac support you would want to be able to build visual applications. When they say they might not include a cross-platform VCL library, I’m guessing this means they intend to add a custom Mac-only library for compiling to Mac, personally i find the thought of this somewhat horrifying, the reason people are so eager to get cross-platform support is obviously to compile their applications to multiple platforms, having more than 1 visual component library needed to do so will obviously complicate things a lot. Because of this I am certainly expecting they will eventually move this feature over to the actual plans for one of the releases.

Read More

Delphi: Thread Variables

A somewhat less known feature of Delphi is thread variables. Thread variables are variables that can contain a different value for each thread in the application. They are defined like regular variables, the only difference is that the “var” keyword is replaced with “threadvar”. In the example below I’ll show you how they work in a small console application. Note that I used the TThread class for convenience, however in reality you’ll only ever need this for procedural code as you can add fields to your TThread subclass to store data in for each thread. The example uses the main thread and a separated thread to show you how it works.

program ThreadVarTest;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;

type
  TTestThread = class(TThread)
  protected
    procedure Execute; override;
  public
    constructor Create;
  end;

threadvar
  TestVar: string;

var
  i: Integer;

procedure Test;
begin
  WriteLn('Original TestVar: ' + TestVar);
  TestVar := 'Asdf' + IntToStr(i);
  Inc(i);
  WriteLn('New TestVar: ' + TestVar);
end;

{ TTestThread }

constructor TTestThread.Create;
begin
  inherited Create(False);
  FreeOnTerminate := True;
end;

procedure TTestThread.Execute;
begin
  Test;
end;

begin
  i := 0;
  Test;
  WriteLn('Starting thread.');
  TTestThread.Create;
  ReadLn;
  WriteLn(TestVar);
  ReadLn; // Prevent window from closing
end.

As you can see when running it, even though the content of the thread variable was changed, the variable was still empty when accessed by the new thread. I’ve added the incremental number to show you that when after you press a key when the thread has exited and you check the thread variable content for the main thread, it will show Adsf0 as it was stored by the main thread originaly.

Read More

Delphi: Decimal color to RGB and back

Converting a decimal color value (24-bit) to RGB in Delphi is easy using bitshifts, the reverse is true as well. Here’s how it’s done:

procedure ColorToRGB(const Color: Integer; out R, G, B: Byte);
begin
  R := Color and $FF;
  G := (Color shr 8) and $FF;
  B := (Color shr 16) and $FF;
end;

function RGBToColor(const R, G, B: Byte): Integer;
begin
  Result := R or (G shl 8) or (B shl 16);
end;

Take in mind that Delphi TColor is a 24-bit integer decimal color representation.

Read More