In general I'd support this but using your example
using b:= Sender as Tbutton do
b.caption := 'Click me!';
Shall b be free'd at the end or not ?
You replaced 'with' with 'using', so yes it will be freed. But that is not what you intended to do I guess.
My example was slightly different, it used 'with'.
I see them as two different things:
'with' would still be the simple and lazy alias thing, like a const parameter variable that is only accessible from within the scope of a procedure and cannot be assigned to.
But this kind of 'with' just reminded me of something ... the using statement in C#:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statementIt is designed for objects implementing the IDisposable interface.
But it could be usefull to have it in Object Pascal too, to ensure objects are getting freed once out of scope.
(and maybe try to call Dispose when using an interface instead of an object)
//technically this would be the shorthand equivalent:
using o := TObject.Create do
begin
//do something with o
end;
//to these inline procedures:
//one for properly freeing:
procedure using(o: TObject); Inline;
begin
try
using_Inner_scope(o);
finally
o.free;
end;
end;
//the inner scope of the using statement:
//o is like a const parameter.
procedure using_Inner_scope(const o: TObject); Inline;
begin
//do something with o;
end;
using (TObject.Create);
I used two inner procedures because freeing a const variable is not possible I think.
The new 'with' would just be (got to admit it
) a lazy shorthand, but 'using' would be a lot more usefull:
Pro's :
- more readable, cleaner, shorter code.
- encourages safer coding: programmers are using try finally implicitly and mistakes with nested try finally's are avoided.
- less verbose, but fits well into the syntax.
- you could wrap things like beginning/ending critical sections (or anything that needs a try finally) in the constructor and destructor of a class and enforce a 'pattern' (1)
- ...
Con's :
- maybe it wil encourages some programmers to write long procedures instead of splitting them up in reusable functions/procedures.
- the difference between 'with' and 'using' could be confusing and programmers could accidently mix them up, resulting in accidently freeing objects or memory leaks.
- (1) could be a disadvantage too because it causes some overhead, but no-one forces you to do this.
Recently I saw this "genius"
shorthand in production delphi code:
with TObject.Create do
begin
//do something with the object...
free;
end;
So wrong on so many levels
, the person who wrote this NEEDS the using statement