DEV Community

Cover image for Code Smell 219 - Looping from index 0
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 219 - Looping from index 0

Counting from zero seems natural. Doesn't it?

TL;DR: Start counting from one instead of zero. Like humans do.

Problems

  • Bijection from real-world broken

  • Cognitive load

  • Overly implementation-oriented code

Solutions

  1. Favor high-level declarative languages

Context

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

Sample Code

Wrong

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])
    }
}

Enter fullscreen mode Exit fullscreen mode

Right

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

Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

This is a language smell.

Exceptions

  • Low-level optimized code

Tags

  • Declarative Code

Conclusion

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.

Relations

More Info

Wikipedia

Disclaimer

Code Smells are my opinion.

Credits

Photo by Andy Kelly on Unsplash


Pay attention to zeros. If there is a zero, someone will divide by it.

Cem Kaner


This article is part of the CodeSmell Series.


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

Book

Top comments (0)