Hardcore Software

How hard it can get?

Thinking of using constants in Delphi? Consider class properties! February 27, 2007

Filed under: .NET,Delphi — Hemant @ 5:39 am
If you have gone through any *real* software project you will understand the need of using constants in code. Your professor would have told you thousand times that don’t use any magic numbers in code and if you need, define a constant and use *that* in code. I wouldn’t go into the flexibility constants brings in (define and change at single place and use million times stuff).

What I want to discuss is an alternative to constant. There are called “class properties”. In C world, these would be called static properties. Yes, you guess right. These are properties which relate to a “class” rather than an “object” (instance of the class). With Delphi.NET, we now have:

  1. Class Fields
  2. Class Methods (Both procedures and functions)
  3. Class Properties

Class fields and class properties and not available in Delphi for Win32 (well, programmers take “never say die” approach).

So class properties allows us to write something like:

var
number: Integer;
begin
number := TPredefinedNumbers.DefaultNumber;
//do something with number
end;

Here, “DefaultNumber” is a class property of TPredefinedNumbers class and we can access DefaultNumber using class name and without actually creating an instance of it. .NET framework makes extensive use of class properties. Refer SystemColors, Brushes etc.

Why class properties qualifies as an (perhaps better) alternative for constants? The reason is, you never know what crazy requirement will be raised by your sales or marketing person which calls for user control on that constant. Perhaps you would think that using the INI file for that constant value would be better so that you can control it. Perhaps day after tomorrow it will qualify to sit in a database field. Who knows?

So class properties provide a great abstraction. When you want to change the location where that constant value resides, all you need to change the get method of class property. And everything works fine..

type
TPredefinedNumbers = class
private
class function GetDefaultNumber: Integer;

published
class property DefaultNumber: Integer read GetDefaultNumber;

end;

implementation

class function TPredefinedNumbers.GetDefaultNumber: Integer;
begin
//You can return a hard coded value
Result := 0;

//or you can get from INI file or database or whatever and return
end;

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