Is Delphi “with” keyword a bad practice?

The biggest danger of with, outside of pathological conditions like “with A, B, C, D” is that your code can silently change meaning with no notice to you. Consider this example:

with TFoo.Create
try
  Bar := Baz;
  DoSomething();
finally
  Free;
end;

You write this code knowing that Bar is a property of TFoo, and Baz is a property of the type containing the method which has this code.

Now, two years later, some well-meaning developer comes in adds a Baz property to TFoo. Your code has silently changed meaning. The compiler won’t complain, but the code is now broken.

Leave a Comment