Tip: scoped constants

I realise this won’t be for everyone, but since Delphi 2005, constants can be defined within classes and record types. While class and record constants are not things I particularly find useful when taken literally as ‘constants attached to a class or record’, I do like how the feature enables the definition of what I call scoped constants, properly grouping related items and lessening the polution of the global namespace. So, instead of doing the following:

const
  DublinCoreURI = 'http://purl.org/dc/elements/1.1/';
  ExifURI = 'http://ns.adobe.com/exif/1.0/';
  MicrosoftPhotoURI = 'http://ns.microsoft.com/photo/1.0';
  TIFFURI = 'http://ns.adobe.com/tiff/1.0/';
  XMPURI = 'http://ns.adobe.com/xap/1.0/';

procedure Test;
var
  S: string;
begin
  S := XMPURI;

you can do this instead:

type
  StandardURIs = record const
    DublinCore = 'http://purl.org/dc/elements/1.1/';
    Exif = 'http://ns.adobe.com/exif/1.0/';
    MicrosoftPhoto = 'http://ns.microsoft.com/photo/1.0';
    TIFF = 'http://ns.adobe.com/tiff/1.0/';
    XMP = 'http://ns.adobe.com/xap/1.0/';
  end;

procedure Test;
var
  S: string;
begin
  S := StandardURIs.XMP;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s