[xquery-talk] XQuery treatment of xs:positiveInteger?

Tegels, Kent Kent.Tegels at hdrinc.com
Tue Jul 20 10:04:52 PDT 2004


Chiming in...

Let's see if I can get back in Per's good graces with this: IMHO, the
compiler really should have a complained about this. Strong type
soundness is hallmark of Xquery.

Now let's see if I can't get Jeni mad at me: I have to disagree with the
"be generous with what you accept." Wouldn't good coding and security
practices say the opposite? If the compiler complained about this (as I
think it should,) then there's no need to cast and type correctness is
more assured. Putting it another way, if I pass my:simple-add(-1,3), I'd
rather have the compiler refuse to do the work rather than failing at
run-time when it tried to cast -1 to positive integer.

Thanks for listening,
Kent

-----Original Message-----
From: talk-bounces at xquery.com [mailto:talk-bounces at xquery.com] On Behalf
Of Jeni Tennison
Sent: Tuesday, July 20, 2004 8:44 AM
To: talk at xquery.com
Subject: Re: [xquery-talk] XQuery treatment of xs:positiveInteger?


Till wrote:
> So the constants '2' and '3' are of type xs:integer and that's a 
> supertype of xs:positiveInteger and as such cannot be substituted.

The lesson here is that to avoid users having to do casts themselves you
should define functions so that they're generous in what they accept.
This is particularly true when it comes to functions that accept numbers
or strings because it's so much easier for someone using your function
to write the literals than the casts. Consider:

  my:simple-add(2, 3)

compared to:

  my:simple-add(xs:positiveInteger(2), xs:positiveInteger(3))

You can do the casts yourself, in the body of the function, and thus you
still get the benefits of the type checking. In this example, something
like:

  declare function my:simple-add($xi as xs:integer,
                                 $yi as xs:integer)
                                as xs:positiveInteger {
    let    $x := xs:positiveInteger($xi),
           $y := xs:positiveInteger($yi)
    return $x + $y
  };

You'll notice that several of the built-in functions are designed in
this way: the actual restrictions on the arguments are described in the
definition of the function rather than via the declared types of the
arguments. For example, see fn:expanded-QName [1].

Cheers,

Jeni

[1] http://www.w3.org/TR/xpath-functions/#func-expanded-QName

---
Jeni Tennison
http://www.jenitennison.com/

_______________________________________________
talk at xquery.com
http://xquery.com/mailman/listinfo/talk





More information about the talk mailing list