Null coalescing operator

From Wikipedia, the free encyclopedia
Jump to: navigation, search

The null coalescing operator (called the Logical Defined-Or operator in Perl) is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#,[1] and Perl as of version 5.10.[2]

C#[edit]

In C#, the null coalescing operator is ??. It is most often used to simplify null expressions as follows:

possiblyNullValue ?? valueIfNull

For example, if one wishes to implement some C# code to give a page a default title if none is present, one may use the following statement:

string pageTitle = suppliedTitle ?? "Default Title";

instead of the more verbose

string pageTitle = (suppliedTitle == null) ? "Default Title" : suppliedTitle;

or

string pageTitle;
 
if (suppliedTitle == null)
    pageTitle = "Default Title";
else
    pageTitle = suppliedTitle;

The three forms are logically equivalent.

The operator can also be used multiple times in the same expression:

return some_Value ?? some_Value2 ?? some_Value3;

Once a non-null value is assigned to number, or it reaches the final value (which may or may not be null), the expression is completed.

CFML[edit]

As of ColdFusion 11[3] or Railo 4.1,[4] CFML supports the null coalescing operator as a variation of the ternary operator, ?:. It is functionally and syntactically equivalent to its C# counterpart, above. Example:

possiblyNullValue ?: valueIfNull

F#[edit]

The null value is not normally used in F# for values or variables.[5] However null values can appear for example when F# code is called from C#.

F# does not have a built-in null coalescing operator but one can be defined as required as a custom operator:[6]

let (|?) lhs rhs = (if lhs = null then rhs else lhs)

This custom operator can then be applied as per C#'s built-in null coalescing operator:

let pageTitle = suppliedTitle |? "Default Title"

Perl[edit]

In Perl (starting with version 5.10), the operator is // and the equivalent Perl code is:

$possibly_null_value // $value_if_null

The possibly_null_value is evaluated as null or not-null (or, in Perl, undefined or defined). On the basis of the evaluation, the expression returns either value_if_null when possibly_null_value is null, or possibly_null_value otherwise. This is similar to the way ternary operators (?: statements) work in languages that support them. The above Perl code is equivalent to the use of the ternary operator below:

defined($possibly_null_value) ? $possibly_null_value : $value_if_null

This operator's most common usage is to minimize the amount of code used for a simple null check.

As with other languages that treat certain non-null values as boolean false (in Perl's case, 0 and the empty string), the boolean or operator "||" is not a null coalescing operator.

  DB<1> print 0 // 1       # A null coalescing operator
0
  DB<2> print 0 || 1       # Not a null coalescing operator
1

Perl additionally has a //= assignment operator, where

a //= b

is largely equivalent to:

a = a // b

SQL[edit]

In Oracle's PL/SQL, the NVL() function provides the same outcome:

NVL(possibly_null_value, 'value if null');

In SQL Server/Transact-SQL there is the ISNULL function that follows the same prototype pattern:

ISNULL(possibly_null_value, 'value if null');

Attention should be taken to not confuse ISNULL with IS NULL – the latter serves to evaluate whether some contents are defined to be NULL or not.

The ANSI SQL-92 standard includes the COALESCE function implemented in Oracle,[7] SQL Server,[8] PostgreSQL,[9] SQLite[10] and MySQL.[11] The COALESCE function returns the first argument that is not null. If no terms are not null, returns null.

COALESCE(possibly_null_value[, possibly_null_value, ...]);

PHP[edit]

Main article: Elvis operator

In PHP (starting with version 5.3), it has been possible to leave out the middle part of the ?: conditional operator, which is also used as a ternary operator, to create a binary operator. Since it first appeared in related languages,[12][13] this has been known as the Elvis operator:

$foo = $foo ? $foo : $bar;
 
$foo = $foo ?: $bar;

This also allows one to easily return a value with less chance of throwing an error if the value is null or undefined:

return $foo ?: $bar;

While this is popular for concise expressions, due to an unfortunate error in the language grammar of PHP, Elvis operators are subject to the same syntax limitations when chained together, as it is considered to be a ternary operator "short-cut".[14] The ternary conditional operator is left-associative in PHP, which is the opposite of the expected behavior; so combining several conditional operators may produce extremely non-intuitive results:[15]

$var =  $foo ? $bar : $bar  ?: $baz;  # is equivalent to:

$var = ($foo ? $bar : $bar) ?: $baz;  $var = $bar ?: $baz
 
# The expected behavior must be specified with parentheses.

$var = $foo ? $bar : ($bar ?: $baz);

Note that, like some others, ?: is not a true null coalescing operator, as it returns the first argument if it evaluates to TRUE in PHP. This is used for loose typing of expressions.

Python[edit]

Python's "or" operator is not a null coalescing operator, as demonstrated below:

>>> 0 or 1
1

If or were a null coalescing operator, it would return the first non-null argument, which is 0. (0 and null, called None in Python, are distinct concepts.) In practice, however, the or operator is sometimes used for this purpose when the left operand is guaranteed not to be 0 or False (or when distinguishing them from None is not important).

Scheme[edit]

In Scheme, "boolean false" and "null" are represented by the same value, written as #f. Furthermore, #f is the only value in Scheme that is treated as false by boolean operators, unlike some other languages, in which values like 0, the empty string, and the empty list may function as false. The boolean 'or' operation, written as (or x y), returns x if it is not false, otherwise it returns y. Thus, in Scheme, there is no need for a separate "null coalescing operator", because the or operator serves that purpose.

Javascript[edit]

In Javascript, null coalescing can be accomplished through the use of a boolean "or" statement:

function setTitle(suppliedTitle) {
   this.title = suppliedTitle || "Default title";
}

Note that this is not a true example of null coalescing due to Javascript's concept of "thruthiness." Because of this, values that Javascript evaluates as false (such as 0 or false) will also be coalesced in the evaluation of the statement, possibly yielding undesirable results.

See also[edit]

References[edit]

  1. ^ ?? Operator (C# Reference)
  2. ^ // Operator (Perl Reference)
  3. ^ Elvis operator
  4. ^ RAILO-2195 add support for the Elvis Operator
  5. ^ Null Values (F# Reference)
  6. ^ Operator Overloading (F# Reference)
  7. ^ http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617
  8. ^ http://technet.microsoft.com/en-us/library/ms174075.aspx
  9. ^ http://www.postgresql.org/docs/9.1/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL
  10. ^ http://www.sqlite.org/lang_corefunc.html
  11. ^ http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce
  12. ^ "coding style - ?: operator PHP". Retrieved 2014-02-17. 
  13. ^ https://github.com/getrailo/railo/wiki/Operators#elvis-operator
  14. ^ "PHP Bug #61915: incorrect associativity of ternary operator". PHP website. 2012-05-02. Retrieved 2014-02-17. 
  15. ^ "Comparison Operators, Example #3". PHP website. Retrieved 2014-02-17.