Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delphi helper class , remove empty strings

Tags:

delphi

in the previous ( remove empty strings from list ) question I asked about the removal of empty strings from a stringlist

....
// Clear out the items that are empty
for I := mylist.count - 1 downto 0 do
begin
  if Trim(mylist[I]) = '' then
    mylist.Delete(I);
end;
....

From the aspect of code design and reuse I would now prefer a solution being more flexible as :

 MyExtendedStringlist = Class(TStringlist)

 procedure RemoveEmptyStrings;

 end;

Q : Can I use a class helper in this case ? How would this look like in contrast to designing a new class as above ?

like image 967
Franz Avatar asked Dec 05 '22 06:12

Franz


1 Answers

A class helper is an excellent idea here. To make it more widely applicable you should choose to associate the helper with the least derived class to which the helper can apply. In this case that means TStrings.

The huge advantage over deriving a new class is that your helper methods are available for instances of TStrings that are not created by you. Obvious examples include the TStrings properties that expose the contents of memos, list boxes etc.

I personally would write a helper that offers a more general removal functionality using a predicate. For instance:

type
  TStringsHelper = class helper for TStrings
  public
    procedure RemoveIf(const Predicate: TPredicate<string>);
    procedure RemoveEmptyStrings;
  end;

procedure TStringsHelper.RemoveIf(const Predicate: TPredicate<string>);
var
  Index: Integer;
begin
  for Index := Count-1 downto 0 do
    if Predicate(Self[Index]) then
      Delete(Index);
end;

procedure TStringsHelper.RemoveEmptyStrings;
begin
  RemoveIf(
    function(Item: string): Boolean
    begin
      Result := Item.IsEmpty;
    end;
  );
end;

More generally, TStrings is an excellent candidate for a class helper. It is missing quite a deal of useful functionality. My helper includes:

  • An AddFmt method that formats and adds in one go.
  • An AddStrings method that adds multiple items in one call.
  • A Contains method that wraps up IndexOf(...)<>-1 and presents a more semantically meaningful method to future readers of code.
  • A Data[] property, of type NativeInt, and matching AddData method, that wraps the Objects[] property. This hides the casts between TObject and NativeInt.

I'm sure there is more useful functionality that could be added.

like image 178
David Heffernan Avatar answered Dec 26 '22 20:12

David Heffernan