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 ?
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:
AddFmt
method that formats and adds in one go. AddStrings
method that adds multiple items in one call.Contains
method that wraps up IndexOf(...)<>-1
and presents a more semantically meaningful method to future readers of code.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With