Suppose I have the following code:
function DoSomething:Boolean; var obj : TMyObject; i : Integer; begin Result := False; //We haven't executed GetValue() correctly yet obj := TMyObject.Create(); try //perform some code that may produce an exception i := obj.GetValue(); //Set the return to True as we executed GetValue() successfully Result := True; finally //do some cleanup obj.Free; end; end;
The Delphi compiler complains that the value assigned by Result is never used on the first line.
I probably miss something obvious, but I donβt understand why the compiler optimizes this (if optimization is enabled).
I have always been taught to explicitly set my variables so as not to confuse their values. In addition, if the GetValue()
function throws an exception, the string Result := True;
will never be executed. Therefore, we are dominated by the fact that Delphi initialized the variable.
So, is this safe / acceptable code? Should I just delete the first line of the method, which makes it difficult to read? Otherwise, I would have to disable the special compiler warning, but I do not want to do this, since this warning message may provide useful information.
source share