Another bug report post! I wrote the first one last year1 and it came to my mind today while fixing a bug. The idea of this post format is to explain a bug I produced and fixed. In order to avoid too much context I will go through a minimal version of today’s bug (in PHP, though language does not matter for this one):

$accumulator = [0,0,0];

foreach($objects as $object) {
  $accumulator[$object->index] = $object->value;
}

I have a list of objects and want to collect their values by their indices. I know that the indices are numbers 0, 1 or 2 so I use a small array to hold the three sums. What initially I got wrong was that multiple objects with the same index are allowed in which case their values should be summed up. The above code just writes the last value into the accumulator instead of adding it. So the fix was a simple plus sign:

$accumulator[$object->index] += $object->value;

The reason it took some time to be discovered is that this case was rare and did not come up during simple execution paths. I guess the underlying issue is that I use a non-key value of one structure ($object->index) as a key value in another structure ($accumulator) so I should think about how to handle multiple entries for the same key.

Take-away: When converting one data structure into another, think about the identifying keys in both and how to handle multiples.