There are no if
statements in XQuery without else
. Return the empty sequence instead ()
, or any reasonable identity element (which is usually what you will require if nothing specific is defined).
if ($foo eq "bar")
then
42
else
()
In contrast to procedural languages, where "no else statement" simply means "do nothing" XQuery is a functional language, which also implies that every operation must have "something" returned. How to proceed "nothing"? It might have been possible to declare "no else
statement means returning the empty sequence instead", but the W3C XML Query working group seems to have decided requiring to explicitely define returning nothing instead. All in all, this results in easier to understand and possibly better code, as you have to think about what the "else" value to return is; as there could be a lot of reasonable values: 0
if you're adding up something, 1
if multiplying, the empty string ""
for joining strings without separators, the empty sequence if joining strings with separators, ...
Do not use "empty return
statements"
Using an "empty" return is not possible, but returns <return/>
children elements in the current context instead, so else return
is merely a else ./return
. This will not only fail (and return something) if the current context indeed has <return/>
children, but also if no context at all is bound.
Do not return empty strings
Returning an empty string does not return nothing, but the empty string, which is a value and might even break typing at another place. Returning the empty string is no general solution, but might be in some specific cases.