between and among: worth Phobosization?

Ola Fosheim Grøstad" <ola.fosheim.grostad+dlang at gmail.com> Ola Fosheim Grøstad" <ola.fosheim.grostad+dlang at gmail.com>
Tue Dec 17 08:07:08 PST 2013


On Tuesday, 17 December 2013 at 14:36:38 UTC, Marco Leise wrote:
>> > boolean result, so why does among have to return an index 
>> > instead of a
>> > boolean true/false?
>> 
>> More info is better than less info, especially if it comes for 
>> free. We already use this idiom in a couple of places in 
>> Phobos.

But it might not be free if the backend is incapable of reducing 
it because it lacks information. Sometimes just using gotos can 
lead to faster code (if they disappear in the IR of the backend 
after loop-unrolling). So testing and tweaking on different 
backends is kind of important (removing structures that inhibit 
optimization).

Some CPUs also will generate 1 as true for you when doing tests, 
which you in turn can use for indexing to avoid branching, so 
what is free depends on the hardware…

> I've always preferred findCharInString() to return the "end"
> of the string in case the char isn't found instead of e.g. -1,
> for two reasons:
>
> a) With an index to the end (equal to the length) you can do
>    more useful stuff like:
>
>    auto idx = findCharInString(' ', str);
>    str = str[idx .. $];

Yep, that is neat, but then you really should name the function 
indexOfCharOrEnd() so you can forget about it when you look at 
the code again. I personally prefer to have boolean alternatives, 
I find the code becomes more readable. And it is sometimes easier 
to optimize a decision-problem than a search-problem.

Still, what is useful depends on what is the common case. When 
writing string validators I just want exceptions and don't even 
care about the result, because the code becomes very easy to 
maintain that way. The result is implied by being able to proceed 
to the next line:

validate_number(record.age);
validate_email(record.email);
database.store(record);


More information about the Digitalmars-d mailing list