返回对象时为什么不直接使用Result变量?

时间:2018-04-17 20:00:00

标签: delphi

我在很多例子中看到过创建一个与Result类型相同的变量,并在函数末尾分配它而不是仅仅使用Result变量。

例如在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;

为什么要创建变量Answer而不是仅使用Result?

这是程序员决定这样做的方式还是背后有原因?

1 个答案:

答案 0 :(得分:5)

  

这是程序员决定这样做的方式还是背后有原因?

这里没有充分的理由使用额外的局部变量。这样做只会增加复杂性。我会这样写:

class function TJSONObject.ParseJSONValue(
  const Data: TArray<Byte>; 
  const Offset: Integer; 
  const ALength: Integer; 
  Options: TJSONParseOptions
): TJSONValue;
var
  Parent: TJSONArray;
  Br: TJSONByteReader;
begin
  Parent := TJSONArray.Create;
  try
    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
        Result := Parent.Pop
      else
        Result := nil; 
    finally
      Br.Free;
    end;
  finally
    Parent.Free;
  end:
end;

这也纠正了生命周期管理和潜在的内存泄漏,如评论中所述。