Reputation: 2143
I'm using PowerBuilder and have a problem with the if condition. I want to check if a variable is not null or it is not empty.
So first I have following if condition to test if the variable is null or not:
IF IsNull(ls_name) THEN
messagebox("ls_name", "is null") //true
else
messagebox("ls_name", "is not null")
end if
From the above condition, I know that ls_name is null. Now I test if its empty or not:
if ls_name = "" then
messagebox ("ls_name", "is empty")
else
messagebox("ls_name", "is not empty") //true
end if
And i get that ls_name is not empty.
Now when I use an if condition to check if ls_name is NOT Null or it is NOT empty, I put the following if condition:
IF not IsNull(ls_name) or ls_name <> "" THEN
messagebox("test", "condition true")
else
messagebox("test", "condition false") //this becomes true.
end if
It goes to the else part of the condition. Shouldn't the if part become true? Am I writing the if condition wrong?
Upvotes: 0
Views: 33172
Reputation: 765
Best technique i use for my programs are
If IsNull(ls_name) THEN ls_name = ""
IF Len(Trim(ls_name)) = 0 THEN
ERR MSG HERE
END IF
i always set null strings to empty spaces then check if the strings are empty.. it also depends on the scenario you are running
Upvotes: 0
Reputation: 6215
Thinking of "null" as "unknown" has always gotten me by in understanding how expressions evaluated.
So, when ls_name is null,
not IsNull(ls_name) or ls_name <> ""
evaluates to
NOT TRUE OR UNKNOWN
or
FALSE OR UNKNOWN
Well, for an OR to evaluate to TRUE, at least one condition must be TRUE. That doesn't apply in this case.
The way I usually test for this is:
IF NOT (IsNull (ls_name) OR ls_name = "") THEN
which, when ls_name is null, resolves to
NOT (TRUE OR UNKNOWN)
then
NOT (TRUE)
and
FALSE
In other words, the variable is "empty".
Good luck,
Terry
Upvotes: 2
Reputation: 11465
Beware of PB manner for testing if
conditions and null behavior:
if
So in your case, it is probable that when ls_name is null the not IsNull(ls_name)
is evaluating to true, but ls_name <> ""
is becoming null, thus true or null
is becoming null and you always going to the else
part.
I would check in 2 times :
if not IsNull(ls_name) then
if ls_name <> "" then
//not empty
else
//empty
end if
else
//null
end if
If you need to handle the same code for not empty / not null then you would have to use some kind of boolean flag. I also starting to use the goto
statement that is handy when dealing with nested if
statement.
(BTW : NO, goto
- when used carefully - is not evil ;o)
Upvotes: 1