[fpc-pascal] A better way?

Ryan Joseph ryan at thealchemistguild.com
Fri Apr 15 08:15:28 CEST 2016


I’ve cleaned up some code by declaring uses in the implementation and using generic untyped variables like TObject for parameters. This compiles but I’m left with lots of ugly type casting in the implementation because the parameters for methods are untyped. Yes it works but I feel like the compiler could be helping more.

Just as an idea to float out here’s a suggestion for a “hint” syntax which would be used to solve the type casting issue by doing some dynamic typing.

Sure you could put those all in file for this example but in the real world there may be dozens of TClassB subclasses which would make the unit 10,000’s of lines long and impossible to navigate. The other solution as mentioned would be to use $includes and still use the single unit approach (how reliable is this? I’ve never tried).

Does this look like more work than using $includes? Maybe I need to seriously considering reorganizing my projects to work like this but it just feels wrong for some reason.

=====================

unit Globals;
interface

type
	HClassB = 'TClassB';	// declare a hint to the class name

implementation
end.

=====================

unit ClassB;
interface
uses
	ClassA;
	
type
	TClassB = class
		procedure DoSomething (sender: TClassA);
	end;

implementation

procedure TClassB.DoSomething (sender: TClassA);
begin
	// full access to TClassA
end;

end.

=====================

unit ClassA;
interface
uses
	Globals;
	
type
	TClassA = class
		// The interface section can't know about TClassB so we declare a
		// class name hint from Globals.pas (HClassB) and assign the paramter with it
		// using the "hint" syntax
		procedure SetValue (value: TObject[HClassB]);
	end;

implementation

// use ClassB now so hints evaluate
uses
	ClassB;

procedure TClassA.SetValue (value: TObject[HClassB]);
begin
	// behind the scenes the compiler (or preparser if FPC has one) replaces the text "TObject[HClassB]" to “TClassB" or throws an error if the identifier TClassB is not found
	value.DoSomething(self);
end;

end.

Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list