Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Calling <code>Free</code> on a null reference is always safe. Go look in the implementation of <code>TObject.Free</code> to see why.</p> <p>This code is an example of a <em>factory function</em>. Its job is to create a new instance of a class, but if it fails, it needs to make sure it doesn't leak a half-created instance when it throws an exception, so it calls <code>Free</code>. When it's sure it's going to succeed, it transfers ownership of the result to the caller. It still calls <code>Free</code>, but if it's already transfered ownership, then it ends up calling <code>Free</code> on a null reference, and there's no harm done. This code is what transfers ownership:</p> <pre><code>Result := Connection; Connection := nil; </code></pre> <p>The way <em>I</em> would write a factory function would do away with the separate <code>Connection</code> variable. I'd construct the result directly in <code>Result</code>, but free it if there were an exception, like this:</p> <pre><code>function TDBXConnectionFactory.GetConnection(const DBXContext: TDBXContext; const ConnectionProperties: TDBXProperties): TDBXConnection; var ConnectionBuilder: TDBXConnectionBuilder; DelegatePath: TDBXDelegateItem; Connection: TDBXConnection; CombinedProperties: TDBXProperties; begin //... ConnectionBuilder := TDBXConnectionBuilder.Create; try //..lots of setting ConnectionBuilder properties ConnectionBuilder.FInputPassword := CombinedProperties[TDBXPropertyNames.Password]; Result := ConnectionBuilder.CreateConnection; try Result.Open; except Result.Free; raise; end; finally ConnectionBuilder.Free; end; end; </code></pre> <p>That has the same effect.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload