protocol for using InputRanges
w0rp
devw0rp at gmail.com
Fri Mar 28 17:24:25 PDT 2014
On Friday, 28 March 2014 at 23:14:56 UTC, Tobias Müller wrote:
> On Thursday, 27 March 2014 at 20:49:16 UTC, Walter Bright wrote:
>> On 3/27/2014 12:21 PM, Rainer Schuetze wrote:
>>> This loop is intuitive. Not being allowed to call empty or
>>> front multiple times
>>> or not at all is unintuitive. They should not be named as if
>>> they are properties
>>> then.
>>
>> I can concede that. But I can't concede being able to call
>> front without first calling empty, or calling popFront without
>> calling empty and front, or requiring 'pump priming' in the
>> constructor.
>
> Disclaimer: I'm a C++ programmer just lurking here, I've never
> actually used D.
>
> I find it very counter-intuitive that 'empty' is required before
> front or popFront.
> Since 'pump priming' in the constructor isn't wanted either, i'd
> suggest the following protocol:
>
> while (popFront())
> {
> front;
> }
>
> popFront is then required to return !empty.
> 'empty' as a separate property getter can stay but is not
> required for the protocol.
>
> This way, it's clear that the work to fetch the next element is
> always done in popFront.
>
> Generally I find dependecies between functions problematic that
> require a specific call sequence. If they can be removed, they
> should.
>
> With my proposed solution, there's still one minor dependency,
> namely that front is not valid before the first popFront. This
> could be solved by again combining the two, as proposed by
> someone else in this thread.
>
> Tobi
Well, it might seem kind of weird at first that an InputRange has
these concepts in three distinct methods, but they really are
three separate operations. After I have spent enough time working
with Java Iterators, I have found it much nicer to be able to get
the current value or see if I'm at the end or not without having
to worry about caching the current value myself. Also as I've
said before it gives you some opportunity to make trying to fetch
something out of an empty range less error prone, because you
don't have to check for a null value, etc.
More information about the Digitalmars-d
mailing list