[fpc-pascal] A better way?

Tony Whyman tony.whyman at mccallumwhyman.com
Fri Apr 15 12:13:36 CEST 2016



On 15/04/16 10:00, Ryan Joseph wrote:
> So, a common scenario is a member variable being declared as TObject then having to typecast it every time I need to access one of it’s methods. Declaring another variable in each function instead of typecasting is perhaps more work but maybe I’m not getting it.
>
> Thanks.
Here's an update of my previous example. In this example, "absolute" is 
just a way of tidying up the code when you need to make multiple 
references to a variable that always has to have its type coerced.

In the end though this is just a "what's in a name? A rose by any other 
name would smell as sweet" debate. No matter how you approach the 
problem, you have to have an identifier for the other class when you 
reference its methods and properties. If you don't want to declare two 
mutually referential classes in the same unit, then one of them (but 
only one) has to use some technique to avoid circular references. Type 
casting is a simple technique and you either have to coerce each use 
(think of TClassB(FObject) as just being a longer name for the same 
thing) or declare an alias of the correct type - a "With" statement can 
also be your friend here.

It's not that big an overhead and when it comes to type casts a 'C' 
programmer would wonder what all the fuss was about.

unit unitA;

interface

type

class TClassA
private
   FClassBObject: TObject;
public
   procedure SomeProc;
end;

implementation

uses unitB;

procedure TClassA.SomeProc;
var aClassBObject: TClassB absolute FClassBObject;
begin
   aClassBObject.OtherProc;
end;

end.




More information about the fpc-pascal mailing list