The only logical recommendation is to pass the listbox as parameter in the function (var is not required).
Dito!!! I'd say the question itself is incorrect (problematic), since the answer is not "good style".
I keep _all_ allocations at the same program depth level, therefore I _never_ return allocated objects from functions.
I know a number of freepascal functions do, but I personally class it as not "good style". An example is FindAllDirectories() in FileUtils:
function FindAllDirectories(const SearchPath : string;
SearchSubDirs: Boolean = True): TStringList;
begin
Result := TStringList.Create;
FindAllDirectories(Result, SearchPath, SearchSubDirs);
end;
Not good. But, its there and, IMHO should be removed.
Its pretty obvious, But, you have these options (there are a few others): (NOTE: I made up code for style demo purposes. The feature implemented here is NOT part of the question)
function ListBoxSearch(AListBox: TListBox; const ANeedle: string): integer;
var
I: integer;
begin
for I := 0 to AListBox.Items.Count - 1 do begin
if SameText(AListBox.Items[I], ANeedle) then begin
Exit(I);
end;
end;
Result := -1;
end;
function StringsSearch(AStrings: TStrings; const ANeedle: string): integer;
var
I: integer;
begin
for I := 0 to AStrings.Count - 1 do begin
if SameText(AStrings[I], ANeedle) then begin
Exit(I);
end;
end;
Result := -1;
end;
type
TStringsHelper = class helper for TStrings
function _Search(const ANeedle: string): integer;
end;
function TStringsHelper._Search(const ANeedle: string): integer;
var
I: integer;
begin
for I := 0 to Count - 1 do begin
if SameText(Self[I], ANeedle) then begin
Exit(I);
end;
end;
Result := -1;
end;
Which can then be used as:
ListBoxSearch(ListBox1, 'something');
StringsSearch(ListBox1.Items, 'something');
ListBox1.Items._Search('something');
As far as "good style". I always namespace my functions by the class type name. Overloading works, but can fail or appear confusing. Class helpers are nice, but I prepend helper functions with an underscore so I know its one of my helpers, and not a class method.
Anyway, those are my thoughts. There are a number of reasons why I adhere to these rules like its a religion.
I guess for everyone, you have to try all kinds of coding methodologies to find what works for you. Lord knows, a lot of my "style" has been questioned by people.