Delphi helper class, delete blank lines

in the previous ( delete empty lines from the list ) question I asked about removing empty lines from the list

....
// 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;
....

In terms of code design and reuse, I would prefer a more flexible solution:

 MyExtendedStringlist = Class(TStringlist)

 procedure RemoveEmptyStrings;

 end;

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

+4
source share
2 answers

Class helper is a great idea here. To make it more widely applicable, you must choose to associate the helper with the least derived class that the helper can apply to. In this case, it means TStrings.

, TStrings, . TStrings, , ..

, . :

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;

TStrings . . :

  • AddFmt, .
  • AddStrings, .
  • A Contains, IndexOf(...)<>-1 .
  • A Data[], NativeInt AddData, Objects[]. TObject NativeInt.

, , .

+9

HelperClass, TStrings, .

:

type
TMyStringsClassHelper = class helper for TStrings
       Procedure RemoveEmptyItems;
    end;

{ TMyStringsClassHelper }

procedure TMyStringsClassHelper.RemoveEmptyItems;
var
 i:Integer;
begin
  for i := Count - 1 downto 0 do
    if Self[i]='' then Delete(i);

end;

procedure TForm5.Button1Click(Sender: TObject);
var
 sl:TStringList;
begin
  sl:=TStringList.Create;
  sl.Add('AAA');
  sl.Add('');
  sl.Add('BBB');
  sl.RemoveEmptyItems;
  Showmessage(sl.Text);
  Listbox1.Items.RemoveEmptyItems;
  Memo1.Lines.RemoveEmptyItems;
  sl.Free;
end;
+7

Source: https://habr.com/ru/post/1535721/


All Articles