[Draft] Adding Safe indexing to Array

I was first going to encourage generalizing this idea to Collection, then I realized the consequences made it a bad idea, possibly even for Array.

If I understand correctly, all dereferencing and other methods that peek at Index values can assume that the value is valid for the corresponding collection instance. You can start with a valid Index state for a Collection by using indices, startIndex, or endIndex. This is a precondition; you have to ensure it before calling any code, but the very premise of your proposal violates this!

I guess this idea can work with IndexDistance, and better: offsets can work with all Collection types, not just Array. It's weird appearance-wise since Index and IndexDistance are the same for Array.

You just have to redo your documentation, but the equivalence between Index and IndexDistance for the most common case (Array) will still make it confusing for newbs. So I still advise not going ahead.

And your 3 motivating examples are bad programming given the current constraints on collection indexes.

  • The set of indexes for two collection instances may not be compatible, even when the same types are involved. So just sticking an index from one collection into another is already illegal. Offsets are compatible, but even then you're supposed to check relative lengths first.
  • Your wrapper's equivalent to Index better be definitively mapping to ones of the inner collection. Your programming is just wrong otherwise. (I'm not completely sure, since your second example is vague. But the vagueness itself is a red flag that you're already not using the inner collection's indexes correctly.)
  • This one is like the first case; you need to check the bounds beforehand.
2 Likes