[fpc-pascal] Class field property access

Sven Barth pascaldragon at googlemail.com
Fri Jun 7 14:08:51 CEST 2019


Ryan Joseph <genericptr at gmail.com> schrieb am Fr., 7. Juni 2019, 14:00:

>
>
> > On Jun 7, 2019, at 2:51 AM, Michael Van Canneyt <michael at freepascal.org>
> wrote:
> >
> > What kind of behaviour are you referring to.
>
> Something wrong with my mail server causing your server to block me (Jonas
> said my server didn’t handle greylisting correctly). Easier to just re-sub
> using gmail for now.
>


Michael meant this:
> But my point is Pascal allows this kind of behavior so why are properties
> different?


> >
> >> Who cares if there is an additional level of indirection?
> >
> > Because the indirection may not be there. The compiler cannot guarantee
> that, thus leading to access violations.
> >
> > You can use a getter function to get the desired property. In the getter
> you
> > can decide what to do: create the b instance (sometimes a valid choice)
> or raise an error.
> >
> > But the compiler cannot take this decision for you, so b.x is not
> allowed.
>
> I really have to question the wisdom of this. The code below works in
> 3.0.4 and is completely safe. I understand there was delphi compatibility
> and problems with published properties however but that could have been
> worked around easily. Maybe it’s a not big deal in the grand scheme of
> things but writing boiler plate like getters/setters is not fun.
>
> type
> TB = class
>   x: integer;
> end;
>
> type
>  TA = class
>   private
>     b: TB;
>   public
>     property x: integer read b.x write b.x;
>     procedure AfterConstruction; override;
> end;
>
>
> procedure TA.AfterConstruction;
> begin
>  b := TB.Create;
> end;
>
> var
>  a: TA;
> begin
>  a := TA.Create;
>  a.x := 100;
>  writeln(a.x);
> end.
>

Only because this example appears safe does not mean that the whole concept
is safe.
A class might initialize b only later on and with a direct property you'll
only get an access violation. So you'll need a getter anyway to provide a
better exception type. Or to dynamically create the object instance.

I see no reason to revert this change.

Regards,
Sven

>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20190607/05e375eb/attachment.html>


More information about the fpc-pascal mailing list