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:
- Class Fields
- Class Methods (Both procedures and functions)
- 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:
number := TPredefinedNumbers.DefaultNumber;
//do something with number
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..
TPredefinedNumbers = class
class function GetDefaultNumber: Integer;
class property DefaultNumber: Integer read GetDefaultNumber;
class function TPredefinedNumbers.GetDefaultNumber: Integer;
//You can return a hard coded value
Result := 0;
//or you can get from INI file or database or whatever and return