All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.delphi.rules.community-delphi.IfThenShortCircuit.html Maven / Gradle / Ivy

There is a newer version: 1.12.1
Show newest version

Why is this an issue?

The IfThen function may cause access violations if used to conditionally access an object that could be nil.

While the IfThen function is conceptually similar to the ternary operator found in other languages, IfThen does not perform short-circuit evaluation. Both arguments are evaluated when the function is invoked, meaning that all code will be run regardless of the result of the condition.

How to fix it

Use a long-form if condition instead, which does perform short-circuit evaluation:

function MyFunc: string;
var
  Foo: TFoo;
begin
  Foo := nil;

  Result := IfThen(Assigned(Foo), Foo.Bar, 'Baz');
end;
function MyFunc: string;
var
  Foo: TFoo;
begin
  Foo := nil;

  if Assigned(Foo) then begin
    Result := Foo.Bar;
  end
  else begin
    Result := 'Baz';
  end;
end;




© 2015 - 2024 Weber Informatics LLC | Privacy Policy