Names with trailing question mark

Jacob Carlborg doob at me.com
Mon Oct 3 23:47:54 PDT 2011


On 2011-10-04 01:37, bearophile wrote:
> 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()?)

Why would you put the question mark after the parentheses. At least in 
Ruby the question mark is part of the method name. This looks better:

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?";

This is not accepted in Ruby. You need a space after the second question 
mark. If this would be implemented I would vote for requiring a space 
after the first question mark as well.

> I vaguely like the idea of using a trailing question mark in predicate names.
>
> Bye,
> bearophile

What about allowing method names like Scala does, containing arbitrary 
symbols.

void ::: (int a) {}

I assume that will complicate the language quite a lot.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list