I've seen in a lot of examples creating a variable with the same type as the Result and assigning to it at the end of the function instead of just using the Result variable in the first place.
For instance in a code inside System.JSON
class function TJSONObject.ParseJSONValue(
const Data: TArray<Byte>;
const Offset: Integer;
const ALength: Integer;
Options: TJSONParseOptions
): TJSONValue;
var
Parent: TJSONArray;
Answer: TJSONValue;
Br: TJSONByteReader;
begin
Parent := TJSONArray.Create;
Answer := nil; { Why not just use Result directly here? }
Br := TJSONByteReader.Create(
Data,
Offset,
ALength,
TJSONParseOption.IsUTF8 in Options
);
try
ConsumeWhitespaces(Br);
if
(ParseValue(Br, Parent, TJSONParseOption.UseBool in Options) = ALength)
and
(Parent.Count = 1)
then
Answer := Parent.Pop; { Why not just use Result directly here? }
Result := Answer;
finally
Parent.Free;
Br.Free;
end;
end;
Why create the variable Answer instead of just using Result?
Is this just the way the programmer decided to do it or is there a reason behind it?
Resultdirectly if you want to. Either way, just be sure to callFreeon the output object if an error occurs before the function exits, or you will have a memory leak (the above code does not have that protection - shame on Embarcadero for that!).Answer := Parent.Pop. It is safe to assume that there isn't. Of course,Parentcould be leaked quote easily.Parentis leaked ifTJSONByteReader.Createraises an exception.