Delphi - value assigned to "x" has never been used

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.

+4
source share
2 answers

The compiler is correct. False to Result is useless, and the only value your function can return is True.

Two possible execution paths:

  • The function does not throw an exception and returns True.
  • The function throws an exception and therefore does not return the value of the result at all.

The solution is simple, remove the line of code that sets Result to False. At this point, it becomes very clear that the return value has no purpose, and you can simply turn the function into a procedure.

+15
source

Your function has only two results. It either returns True , or throws an exception, so instead you can turn it into a procedure to warn about it.

If you want the result of the False function when GetValue() throws an exception, you must commit this exception to DoSomething and set the return value to False . In this case, you must start your function by initializing the return value to True .

Something like that:

 function DoSomething:Boolean; var obj : TMyObject; i: Integer; begin Result := True; obj := TMyObject.Create(); try try i := obj.GetValue(); except Result := False; end; finally obj.Free; end; end; 
+4
source

All Articles