Names with trailing question mark

bearophile bearophileHUGS at lycos.com
Mon Oct 3 16:37:29 PDT 2011


Predicates are quite common. In D I presume the standard way to write them is with a name like "isFoo". In other languages they are written in other ways:


if (foo.isEven) {}
if (foo.isEven()) {}
filter!isEven(data)

if (foo.evenQ) {}
if (foo.evenQ()) {}
filter!evenQ(data)

if (foo.even?) {}
if (foo.even?()) {}
filter!even?(data)

Other usages:

contains?
areInside ==> inside?


I don't remember serious recent discussions here about that last form. Allowing a single trailing question mark in D names has some advantages:

1) It gives a standard way to denote a predicate, so it becomes very easy to tell apart a predicate from other non predicate things.

2) It allows for short names.

3) A single question mark is easy and quick to write on most keyboards.

4) It is used in other languages, as Ruby, and people seem to appreciate it.

5) Its meaning is probably easy enough to understand and remember.



Some disadvantages:
1) "?" makes code less easy to read aloud.

2) It is less good to use the trailing "?" in functions that aren't properties, the syntax becomes less nice looking:
if (foo.even()?)

3) The usage of the trailing "?" in names forbids later different usages for it, like denoting nullable types.

4) In expressions that use the ternary operator and a property predicate (without leading ()) it becomes a bit less easy to read (example from http://stackoverflow.com):

string customerName = user.loggedIn? ? user.name : "Who are you?";

I think this too gets accepted:
string customerName = user.loggedIn??user.name:"Who are you?";

I vaguely like the idea of using a trailing question mark in predicate names.

Bye,
bearophile


More information about the Digitalmars-d mailing list