是德尔福“与"吗?关键字不好的做法? [英] Is Delphi "with" keyword a bad practice?

查看:26
本文介绍了是德尔福“与"吗?关键字不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关 delphi 中 with 关键字的坏消息,但在我看来,如果您不过度使用它.它可以让你的代码看起来很简单.

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.

我经常把我所有的 TClientDataSets 和 TFields 放在 TDataModules 中.所以在我的表单中我有这样的代码

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;

如果没有 with 关键字,我必须像这样编写代码

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;

我认为使用 with 关键字更容易阅读.

I think is easier to read using the with keyword.

我应该避免使用 with 关键字吗?

Should I avoid using the with keyword?

推荐答案

在with A、B、C、D"等病态条件之外,with 的最大危险是您的代码可以默默地改变含义,而无需通知你.考虑这个例子:

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;

您编写此代码时知道 Bar 是 TFoo 的一个属性,而 Baz 是包含具有此代码的方法的类型的属性.

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.

现在,两年后,一些好心的开发人员进来为 TFoo 添加了 Baz 属性.您的代码已悄然改变了含义.编译器不会抱怨,但代码现在坏了.

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.

这篇关于是德尔福“与"吗?关键字不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆