2

Is there a way to remove part of condition in IF statement depending if I need it or not. Next code is example, because in my code there are a lot of user defined functions and procedures in my language:

IF A THEN
Q := TQuery.Create(Application);
IF B AND C AND D AND E AND Q.FieldByName('Example').AsInteger = 1 then
BEGIN
...
END

So, let's say after creating TQuery that I have imported some data into it (I didn't write that part of code here). Is there a way to remove part with Q in the second IF statement if the Q wasn't created (because the condition A was not satisfied) or do I have to writhe the whole IF statement again just without Q part?

I was thinking using something like CASE to check if Q is created and if it is not, just to skip that part of sentence. If it is possible, how can I skip it?

  • Put begin after the if statement and end after the current end statement! – Dsm Dec 06 '17 at 12:35
  • @Dsm But I need second `IF` to execute every time, no matter if condition `A` was satisfied. Just if `A` is not satisfied, I need second `IF` to be executed without `Q` part. And if I put `BEGIN` and `END` as you say, every time `A` is not satisfied, the second `IF` wouldn't execute also. –  Dec 06 '17 at 12:40

1 Answers1

3

Quick and dirty way

IF B AND C AND D AND E AND (NOT A OR Q.FieldByName('Example').AsInteger = 1) then

As a note, try to keep your if conditions simpler.

EvaluationRequested := A AND C ...
QueryNeedsAval := NOT A OR ... 
if EvaluationRequested AND QueryNeedsAval then 
begin
   ...
end;
Jan Doggen
  • 8,799
  • 13
  • 70
  • 144
ReneA
  • 516
  • 2
  • 7
  • That's what I was looking for. Thank you buddy. –  Dec 06 '17 at 13:03
  • 3
    @nikname if the condition is really whether or not Q was created, I would rather go with `(not Assigned(Q) OR (Q.FieldByName('Example').AsInteger = 1))`. That avoids to duplicate the condition A. Just need to make sure to initialize it to nil. – Ken Bourassa Dec 06 '17 at 15:10
  • I have already fix that problem by inserting a `Boolean variable` which is `TRUE` if condition `A` is not satisfied and if it is satisfied, my code looks like this: `booleanVariable := Q.FieldByName('Example').AsInteger = 1`. The new problem I am facing here is that when there is nothing in `Q.FieldByName('Example').AsInteger`, not even a `NULL` value, my `booleanVariable` never gets assigned. `Q.FieldByName('Example').AsInteger` is empty because the background `SQL` which executes is not returning anything because of it's conditions. –  Dec 07 '17 at 08:45