[xquery-talk] a conceptual clarification

Bas de Bakker bas at x-hive.com
Fri Mar 4 13:41:12 PST 2005

Shadowing a variable with another variable with the same name is 
possible in many languages, including Java.  It is also generally 
confusing and therefore considered bad practice (although I do not agree 
that it should be disallowed).  In this respect there is nothing special 
about XQuery.

I fail to see why you would consider using a let statement within a for 
statement to be confusing, nor do I see a better alternative.  This is 
just like

for (int i = 0; i < n; ++i) {
     Object object = a[i];
     // Use object

in Java, which is an extremely common way of programming in many languages.

Bas de Bakker

Amitabh Ojha wrote:
> Dear Sir,
> It has been a very useful exchange of  messages/ replies from experts on 
> this theme. However, no discussion has taken place as yet on  one point 
> which I had flagged earlier.  I elaborate it here. 
> It is evident now  that  it is a bad practice to have two let 
> statements, one after the other, define a variable  with the same name,  
> as  is  cited  in the following example  (even if it is not illegal as 
> per XQuery Specs)
> let $x := ……
> let $x := ……
> Following from this, will it be correct to assume that  the appearance 
> of a let statement after a for statement be also treated as equally 
> undesirable and error-prone programming technique in XQuery (because in 
> course of  iteration,  a let statement is then forced to rebind  the 
> same variable name say  $x several times, probably forcing it to bind to 
> a new value each time).  I cite two examples here. In case of  my:foo () 
> the result is same as one would expect in Java i.e  1, 2, 3, 4, 5. But 
> in case of  my:bar () we get 101, 102, 103, 104, 105 – this is not what 
> a Java programmer will expect (although in XQuery context one knows why 
> it is so).
> declare function my:foo ()
> {
> for $i in (1 to 5)
> let $x := $i
> return $x
> };
> declare function my:bar ()
> {
> let $x := 100
> for $i in (1 to 5)
> let $x :=  $x  +  $i
> return $x
> };
> Regards.
> Amitabh Ojha

More information about the talk mailing list