Quantcast
Channel: Planet Object Pascal
Viewing all articles
Browse latest Browse all 1725

The Wiert Corner - irregular stream of stuff: jpluimers

$
0
0

A bit more than a year ago, I wrote about Delphi: you should avoid the `with` statement as it makes your code less future proof. That caused some nice comments on the blog, and some more on LinkedIn where Paul Foster mentioned it in a thread ‘Jeoren Pluimers makes a case against “with” statements.‘ Both interesting reads, especially the reasons that people use or avoid with, or keep its use in balance. There is one set of comments I want to emphasize: refactoring multiple with statements into a one function and a call per former with.

Mark Stolworthy: I think when used simply the code becomes easier to read ?

with pdata do
begin
  DatabaseName := pDB.databasename;
  TableName := 'Xdata';
  readonly:=Preadonly;
  FieldDefs.clear;
  IndexDefs.clear;
end;

with pitem do
begin
  DatabaseName := pDB.databasename;
  TableName := 'Xitem';
  readonly:=Preadonly;
  FieldDefs.clear;
  Indexdefs.clear;
end;

I disagree with code like that, as it is very easily refactored into something like this:

Jeroen Pluimers• @Mark, Your code should be refactored to use a method, similar to the example at http://wiert.me/2013/03/27/delphi-you-should-avoid-the-with-statement-as-it-makes-your-code-less-future-proof/#comment-17355 Also if this is from production code, you should use code-completion to make sure the casing of the members is correct.

Initialize(PData, pDB, 'Xdata', PReadOnly);
Initialize(PItem, pDB, 'Xitem', PReadOnly);

procedure TMyClass.Initialize(MyDataSet: TMyDataSet; MyDataBase: TMyDatabase; string TableName; ReadOnly: Boolean);
begin
  MyDataSet.DatabaseName := MyDataBase.DataBaseName;
  MyDataSet.TableName := TableName;
  MyDataSet.ReadOnly := ReadOnly;
  MyDataSet.FieldDefs.Clear();
  MyDataSet.IndexDefs.Clear();
end;

–jeroen

PS: funny to see I officially hate hate hate the WITH statement got posted this week too, as my post above had been in the blog queue more than a year ago: since 20130505 (:


Filed under: Delphi, Delphi 1, Delphi 2, Delphi 2005, Delphi 2006, Delphi 2007, Delphi 2009, Delphi 2010, Delphi 3, Delphi 4, Delphi 5, Delphi 6, Delphi 7, Delphi 8, Delphi XE, Delphi XE2, Delphi XE3, Delphi XE4, Development, Software Development

Viewing all articles
Browse latest Browse all 1725

Trending Articles