Hacker News new | past | comments | ask | show | jobs | submit login

I've spent a lot of time in both domains, and the Python-style half-open interval is the clear winner, because it produces the fewest "+1" and "-1", each and every one of which is begging to be a bug. I disagree with Dijkstra on some other counts, but in this case he is correct, both in theory and in practice.

It's easier today than it used to be 1 indexed, though, because there are more languages that support some form of

    for element in collection: ...
instead of the incredibly error-prone

    for (int i = 0; i < something; i++) { ... }
Or, was it

    for (int i = 0; i <= something; i++) { ... }
Or was it

    for (int i = 1; i <= something + 1; i++) { ...}
You have fewer places to make fencepost errors when you use the first style, so the costs of 1-based indexing are fewer. They're still higher than Python-style, though, because in Python you have both the correct for loop and still have the correct intervals.



When I started programming I quickly found that 0-based indexing was generally simpler. A lot of the time, it makes no difference one way or the other (because you're only using indexes to get at each item in turn, so you just memorize the boilerplate for whichever language you're using), but the moment you introduce ranges, or try to convert dimensionality - particularly with random access - or do some wraparound, or try to implement something like a ring buffer, it's all too easy to come a cropper. Either you put "1+" on every array access, which is error-prone, or you try to manage two different "spaces" (the 0-based one that's the ideal representation and the 1-based one used for indexing) and carefully convert between them... which is error-prone too.

Alternatively, you could just decide to start indexing at zero.

...or you could stick with 1-based indexing, it's up to you. The right thing to do doesn't become wrong just because you don't do it ;)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: