Is Delphi "with" keyword a bad practice?

Marioh picture Marioh · Feb 5, 2009 · Viewed 11.5k times · Source

I been reading bad things about the with keyword in delphi but, in my opinion, if you don't over use it. It can make your code look simple.

I often put all my TClientDataSets and TFields in TDataModules. So in my forms I had code like this

procedure TMyForm.AddButtonClick(Sender: TObject);
begin  
  with LongNameDataModule do
  begin
     LongNameTable1.Insert;
     LongNameTable1_Field1.Value := "some value";
     LongNameTable1_Field2.Value := LongNameTable2_LongNameField1.Value;
     LongNameTable1_Field3.Value := LongNameTable3_LongNameField1.Value;
     LongNameTable1_Field4.Value := LongNameTable4_LongNameField1.Value;
     LongNameTable1.Post;
  end
end;

without the with keyword I have to write the code like this

    procedure TMyForm.AddButtonClick(Sender: TObject);
    begin            
      LongNameDataModule.LongNameTable1.Insert;
      LongNameDataModule.LongNameTable1_LongNameField1.Value := "some value";

      LongNameDataModule.LongNameTable1_LongNameField2.Value :=
               LongNameDataModule.LongNameTable2_LongNameField1.Value;

      LongNameDataModule.LongNameTable1_LongNameField3.Value :=
               LongNameDataModule.LongNameTable3_LongNameField1.Value;

      LongNameDataModule.LongNameTable1_LongNameField4.Value :=
               LongNameDataModule.LongNameTable4_LongNameField1.Value;

      LongNameDataModule.LongNameTable1.Post;
    end;

I think is easier to read using the with keyword.

Should I avoid using the with keyword?

Answer

Craig Stuntz picture Craig Stuntz · Feb 5, 2009

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.