Mexican Delphi specialist Al Gonzalez has made
a proposal to upgrade the WITH keyword that I think it's worth to be discussed. We are discussing it at the
Club Delphi forums.
As you know, WITH keyword seems to be doomed as it's tagged as
dangerous. The proposal is something like this:
WITH TForm2.Create (NIL) DO
TRY
AppLogger.LogForm (WITH);
WITH.ShowModal
FINALLY
WITH.Free
END
- No more than one object/record per WITH block.
- No nested WITH blocks allowed.
- Mandatory WITH keyword or other symbol to indicate the referenced object.
Original post.Somebody noted
something similar in Python:
with open('file.txt', 'r') as f:
f.read()
d.write(...)
Other proposals (in the same thread at Club Delphi) are:
WITH TForm2.Create (NIL) DO
TRY
&ShowModal
FINALLY
&Free
END
and
WITH TForm2.Create (NIL) DO
TRY
.ShowModal
FINALLY
.Free
END
There's also
a proposal to declare an alias:
WITH Obj: TForm2.Create (NIL) DO
TRY
Obj.ShowModal
FINALLY
Obj.Free
END
Or use a default naming like SELF or RESULT.
The proposal is "IT".
My opinion is mixed. I don't like WITH. Years ago I used it a lot in a big project and now it's hard to read that code, so now I used it a few times, mostly in small code snipets like:
(* Initializes state. *)
PROCEDURE TGeckoMovement.Enter;
BEGIN
WITH TgoiGecko (StateMachine.Owner) DO
BEGIN
InicitAnimation (FP_WALK, FP_WALK + NUM_FP_CALK, V_ANIMATION);
Flipped := (Random (2) = 1)
END
END;
But sometimes I use something like:
(* Initializes state. *)
PROCEDURE TGeckoMovement.Enter;
VAR
Gecko: TgoiGecko;
BEGIN
Gecko := TgoiGecko (StateMachine.Owner);
Gecko.InicitAnimation (FP_WALK, FP_WALK + NUM_FP_CALK, V_ANIMATION);
Gecko.Flipped := (Random (2) = 1)
END;
I think that a redefinition would be useful.
What do you think?