IndexNextUpPreviousUrbi SDK 2.7.5

Chapter 18
Urbi Guideline

 18.1 urbiscript Programming Guideline
  18.1.1 Prefer Expressions to Statements
  18.1.2 Avoid return

18.1 urbiscript Programming Guideline

18.1.1 Prefer Expressions to Statements

Code like this:

 
if (delta) 
  cmd = "go"
else if (alpha) 
  cmd = "turn" 
else 
  cmd = "stop";  

is more legible as follows:

 
cmd = 
  { 
    if      (delta) "go" 
    else if (alpha) "turn" 
    else            "stop" 
  };  

18.1.2 Avoid return

The return statement is actually costly, because it also in charge of stopping all the event-handlers, detached code, and code sent into background (via ‘,’ or ‘&’).

In a large number of cases, return is actually used uselessly. For instance instead of:

 
function inBounds1(var x, var low, var high) 

  if (x < low) 
    return false; 
  if (high < x) 
    return false; 
  return true; 
}|; 
assert 

  inBounds1(1, 0, 2);    inBounds1(0, 0, 2);  inBounds1(2, 0, 2); 
  !inBounds1(0, 1, 2);  !inBounds1(3, 0, 2); 
};  

write

 
function inBounds2(var x, var low, var high) 

  if (x < low) 
    false 
  else if (high < x) 
    false 
  else 
    true; 
}|; 
assert 

  inBounds2(1, 0, 2);    inBounds2(0, 0, 2);  inBounds2(2, 0, 2); 
  !inBounds2(0, 1, 2);  !inBounds2(3, 0, 2); 
};  

or better yet, simply evaluate the Boolean expression. As a matter of fact, returning a Boolean is often the sign that you ought to “return” a Boolean expression rather that evaluate it in a conditional, and return either true or false.

 
function inBounds3(var x, var low, var high) 

  low <= x && x <= high 
}|; 
assert 

  inBounds3(1, 0, 2);    inBounds3(0, 0, 2);  inBounds3(2, 0, 2); 
  !inBounds3(0, 1, 2);  !inBounds3(3, 0, 2); 
};