[fpc-pascal] class constants

Jonathan Benedicto contact at jomitech.com
Thu Jan 24 15:25:07 CET 2008


Henry Vermaak wrote:
>> I'm not sure what you mean - do you mean would I be willing to write the
>> support myself?
>
> i think he's asking what the use of it is.  number 2 under the link he 
> gave.

Oh, ok. Well, I'll try to summarize:

Class constants add the ability to provide scoped, "namespaced" constants. 
Although one can handle basic scoping with global constants, by placing them 
in interface vs implementation, they were not designed to be scope-limited. 
They also do not provide a way to group several constants under a common 
name, though one can simulate this functionality using creative constant 
names.

Some of the benefits of class constants are: 1. They provide object-oriented 
constants, 2. They simplify coding by saving the developer from having to 
write long constant names to distinguish global constants from each other. 
3. They reduce coding errors due to the ability to only make public what is 
necessary, keeping what is visible to outside units/classes to a mimimum.

I'm sure that there are other benefits, I just can't think of them off the 
top of my head.

Personally, the main reason I need them is for compatibility. I have a large 
Delphi codebase that I'm porting to FPC and it uses class constants all over 
the code.

Here is an example of their use:

-- Start of Unit1.pas --
unit Unit1;

interface

type
  TTest = class
    private
      const PrivateConst = '1';
    public
      const PublicConst = '1';

      constructor Create;
  end;

implementation

constructor TTest.Create;
var
  Str: String;
begin
  Str := PrivateConst;
  Str := PublicConst;
end;

end.
-- End of Unit1.pas --

-- Start of Unit2.pas --
unit Unit2;

interface

type
  TTest2 = class
      constructor Create;
  end;

implementation

uses
  Unit1;

constructor TTest.Create;
var
  Str: String;
begin
  Str := TTest.PrivateConst; // Will cause compiler error because 
PrivateConst is not visible to this class.
  Str := TTest.PublicConst;
end;

end.
-- End of Unit2.pas --

Jon 




More information about the fpc-pascal mailing list