Counting from zero seems natural. Doesn't it?
TL;DR: Start counting from one instead of zero. Like humans do.
-
Bijection from real-world broken
-
Cognitive load
-
Overly implementation-oriented code
- Favor high-level declarative languages
Low-level languages force you to think at a machine level.
Hardware turning machines were designed to use binary gates and start indexing at 0.
A few programming languages use one-based indexing, where indexing starts from 1.
These languages are known for being higher level and more declarative:
- Basic / Visual Basic
- Pascal
- Smalltalk
- Fortran
- Lua
- MATLAB
- R
- Julia
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30, 40, 50}
for i := 0; i < len(numbers); i++ {
// Iteration goes from zero to len-1
fmt.Println(numbers[i])
}
}
numbers = [10, 20, 30, 40, 50];
% Looping through the array using one-based indexing
% from 1 to length
for currentIndex = 1:length(numbers)
disp(numbers(currentIndex));
end
[X] Automatic
This is a language smell.
- Low-level optimized code
- Declarative Code
We need to think as humans when we code and not as machines.
Humans count from one.
Zero number was a brilliant discovery in math and science but it does not apply to everyday counting.
Code Smell 53 - Explicit Iteration
Code Smell 123 - Mixed 'What' and 'How'
Code Smells are my opinion.
Photo by Andy Kelly on Unsplash
Pay attention to zeros. If there is a zero, someone will divide by it.
Cem Kaner
Software Engineering Great Quotes
This article is part of the CodeSmell Series.
How to Find the Stinky Parts of your Code
My new book about clean code is available for pre-order.
You will find several recipes like this one with a higher level of detail