How do you safely deal with range.front?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Dec 30 20:22:25 UTC 2017


On Saturday, December 30, 2017 19:11:20 aliak via Digitalmars-d-learn wrote:
> On Friday, 29 December 2017 at 20:33:22 UTC, Jonathan M Davis
>
> wrote:
> > Well, I don't know what you're really doing in code here, but
> > in general, you'd write your code in a way that it checks empty
> > and simply doesn't try to do anything with front if the range
> > is empty.
>
> Yes, ideally, if programmers were perfect, this would work. The
> same applies to always checking null before dereferencing a
> pointer. You can of course try and make sure you always do check
> first. Or you can provide a safe way to do it in cases where you
> only want to dereference a pointer if the pointer is not null.
> Granted in some situations you want to crash as well because it
> would indeed be a bug if a pointer was null (or a range was
> empty).
>
> Btw, it seems that phobos, or at lest some of it, has an
> assert(!empty, "Attempting to fetch the front of an empty
> filter."). I guess probably it's not everywhere so hence the
> weird behavior you say happens sometimes :(  ... ah well.

Some ranges do use assertions to check stuff like that, but there is zero
guarantee that a range is going to do that, and the checks won't be there
with -release. So, you might sometimes catch mistakes that way, but you
can't rely on it any more than you can rely on any stray programming bug
being caught. At some point, you simply have to do your best to not write
bugs and write thorough enough unit tests to be reasonably sure that you've
caught whatever you missed. There's nothing special about ranges in that
regard.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list