How to overcome long-circuit evaluation

Share this topic:



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 light and quick, but the second is very heavy and slow (because so are dinosaurs it goes to the database). 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")

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: 112
Joined: 19 Feb 2013, 20:33

Return to Tips and Tricks

Who is online

Users browsing this forum: No registered users and 1 guest


How to overcome long-circuit evaluation

Share this topic:


If you think that this site is not too bad, please LIKE it in Facebook. Thanks!





free counters

eXTReMe Tracker