I wrote this function wich compares string and return TRUE if it matches and FALSE if it doesn’t.
The only problem is that when I compile, I get an error saying that the result can be undefined. I know this is not a problem as there are only 2 possible outcome in this particular situation but I’m kind of a perfectionnist and I want to get better.
Can any of you enlighten me?
function filterUPC(upc: String): Boolean;
var
i, pos1: integer;
Plano: TStringList;
upcPlano: String;
begin
Plano := TStringList.Create;
if (fmMain.lblPlanook.Visible) and
not (fmMain.lblPlanook.Caption = 'INCOMPATIBLE') then
begin
Plano.LoadFromFile(fmMain.ebPlano.Text);
for i := 0 to Plano.Count - 1 do
begin
pos1:=AnsiPos(';', Plano[i]);
upcPlano := AnsiMidStr(Plano[i], pos1 + 1, 12);
if (upc = upcPlano) then
begin
Result := TRUE;
Break;
end
else if (i = Plano.Count - 1) then
begin
Result := FALSE;
end;
end;
end
else
begin
Result := FALSE;
end;
Plano.Free;
end;
Your result is undefined if
Planois empty. In that case, the for-loop never executes andResultis never set.Also, you should really wrap the TStringList create/free in a try/finally (since you’re a perfectionist 😉
Here’s what I would do:
I’ve added
Result:=FALSE;to the top, and removed theelsechecks. The try/finally guarantees that Plano will be freed, even if an exception is raised.