Posts Tagged ‘programming’

When programming we should have 1 based index

December 21st, 2020

It is a bold statement.

Well… is it?

IIRC the most usual, unwanted, exception we get is null reference error.
The second is off-by-one error.

The off-by-one error is the result of us programmers on remembering to subtract one from an index, or subtracting once too many.

Alas we should have 1 based index, like natural language, and let the computer do the subtraction.

What…? That is not how computers work!

No.

But that is how Humans work.

It is many years since we stopped arguing that a computer wants its data layed out such and therefore we adopt to it. Today we try to solve business problems, not computer problems (your domain may vary). We use higher level language. We name our variables after the domain. We use domain language.

We do not ask the customer for the zeroth invoice. And when we ask for the 2nd invoice we expect the 2nd invoice in a list.

The reason for 0 based index is, I believe, a historical technical reason.

When programming assembler, it is easy to point to a memory position and then add an index. Hence having a zero based index is a natural thing; we solve a computer problem.
Then C, a higher level language, comes along. It is way above assembler but is till constructed to be close to the physical machine to be easy to implement on any processor. By that time we still solved computer problems and keeping a zero based index was probably a no brainer.

Then came Java and C#. They try to look like C/C++ due to reasons of not-thinking-things-through and it-is-easier-to-not-move-the-cheese. They keep the zero based index even though they didn’t have to. So now we are stuck with it.

Until either 1) we invent a new operator

1
myArray@1
or
1
myArray/1/
or 2) invent a yet new language.

Until then: Keep spreading the word that we should have a 1 based index.