How to overcome long-circuit evaluation


Link to this posting

Postby Ursego » 19 Feb 2013, 21:39

Unfortunately, the PowerScript programming language doesn't support the short-circuit evaluation of Boolean expressions - the evaluation is always "long-circuit" :cry: . Let's suppose we have Boolean functions uf_is_bird() and uf_is_dinosaur(); the first one is very lightweight and quick (just as a bird), but the second is very heavy and slow (just as a dinosaur). If you have come to PowerBuilder from a programming language which supports the short-circuit evaluation (and almost all the languages support it!), you can mistakenly write:

Code: Select all
lb_is_bird_or_dinosaur = (uf_is_bird() or uf_is_dinosaur())

or (if you are returning a value from a Boolean function)

Code: Select all
return (uf_is_bird() or uf_is_dinosaur())

You can suppose, that uf_is_dinosaur() will not be called if uf_is_bird() has returned true, but you are wrong: uf_is_dinosaur() will be executed ALWAYS. So, express yourself in one of the following ways:

Code: Select all
lb_is_bird_or_dinosaur = uf_is_bird()
if not lb_is_bird_or_dinosaur then lb_is_bird_or_dinosaur = uf_is_dinosaur()

or

Code: Select all
lb_is_bird_or_dinosaur = false
if uf_is_bird() then lb_is_bird_or_dinosaur = uf_is_dinosaur()

or (if you are returning a value from a Boolean function)

Code: Select all
if uf_is_bird() then return true
if uf_is_dinosaur() then return true
return false

It was an OR relation, but the same problem exists with an AND. In the following example, the condition ll_row > 0 will not protect against failure when ll_row = 0 (as a Java or C# developer could think):

Code: Select all
lb_from_usa = (ll_row > 0 and dw_addr.object.country[ll_row] = "US") // runtime error if the DW is empty!

To use ll_row > 0 as a protection, write this way:

Code: Select all
lb_from_usa = false
if ll_row > 0 then lb_from_usa = (dw_addr.object.country[ll_row] = "US")

Remember about that when you are trying to make you code safer using the IsValid() function. The following example, written in the Java/C# style, is dangerous - if the object has not been created, you will get a run-time error:

Code: Select all
if IsValid(ids_XXX) and ids_XXX.RowCount() > 0 then...

The correct solution is obvious:

Code: Select all
if IsValid(ids_XXX) then
   if ids_XXX.RowCount() > 0 then...
end if
User avatar
Ursego
Site Admin
 
Posts: 143
Joined: 19 Feb 2013, 20:33



Ketones are a more high-octane fuel for your brain than glucose. Become a biohacker and upgrade yourself to version 2.0!



cron
Traffic Counter

eXTReMe Tracker