IndexNextUpPreviousUrbi SDK 3.0.0

Chapter 15
Urbi Guideline

 15.1 urbiscript Programming Guideline
  15.1.1 Prefer Expressions to Statements
  15.1.2 Avoid return

15.1 urbiscript Programming Guideline

15.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" 
  };  

15.1.2 Avoid return

The return statement (Section 20.3.3) is actually costly, because it is 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 useless. 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 than evaluating that Boolean value using a conditional, and return either true or false.

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

  low <= x <= high 
}|; 
assert 

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