[fpc-pascal] Better usage of "with"
Sven Barth
pascaldragon at googlemail.com
Thu Jun 14 11:25:20 CEST 2018
Ryan Joseph <ryan at thealchemistguild.com> schrieb am Do., 14. Juni 2018,
10:03:
> type
> TEntity = record
> position: TVec2;
> end;
> TEntityPtr = ^TEntity;
>
> type
> TDoor = record
> with entity: TEntityPtr; // import entity namespace for
> entire TDoor scope
> state: boolean;
> end;
>
> var
> door: TDoor;
> begin
> door.entity := GetAvailableEntity; // pop an entity from
> storage
> door.position := V2(1, 1); // entity is “with” so we
> get access to its members (door.entity^.position)
>
Something like that only leads to confusion. Pascal is a rather explicit
language so manually declaring a Position property inside TDoor would be
more in the spirit of the language.
A possible alternative would be generic type helpers, like this (just an
example, not working code):
=== code beging ===
type
generic TEntityUserHelper<T> = type helper for T
private
function GetPosition: TVec2D; inline;
procedure SetPosition(constref aValue: TVec2D); inline;
public
property Position: TVec2D read GetPosition write SetPosition;
end;
function TEntityUserHelper.GetPosition: TVec2D;
begin
Result := Self.Entity^.Position;
end;
procedure TEntityUserHelper.SetPosition(constref aValue: TVec2D);
begin
Self.Entity^.Position := aValue;
end;
type
TDoor = record
Entity: PEntity;
State: Boolean;
end;
TDoorHelper = specialize TEntityUserHelper<TDoor>;
var
door: TDoor;
begin
// init door
door.Position := Vec2D(21, 42);
end;
=== code end ===
> // works with function parameters also.
> // this is almost like a class helper or at very least mimics “self” in
> methods.
>
> procedure OpenDoor(with var door: TDoor);
> begin
> state := true; // with imports door namespace into entire function
> scope
> end;
>
The declaration of the function (in the interface section) would need to
contain the "with" as all parameters have to match (and its only that parts
are removed from the definition (default parameters, modifiers), but not
the other way around) and thus the declaration would "spill" information
about the function while not needing to.
And again I think that as an expressive language the explicit usage of a
"with" block is better than something like this. Please also not that there
are people out there that advocate *against* the usage of "with" at all as
it is likely to introduce bugs with it.
Regards,
Sven
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20180614/f42c35c5/attachment.html>
More information about the fpc-pascal
mailing list