Do all the things like ++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatarSign Up
Get a devDuck
Rubber duck debugging has never been so cute! Get your favorite coding language devDuckBuy Now
Search - "-20 array index"
In my first summer at my internship I was fixing up a PHP script that a previous developer wrote... It collected our customer's emails and sent them to MailChimp for marketing.
The SQL query to get the emails was pretty standard, but what he did next was not.
There were for loops nested 3 deep. The outer loop's counter was i. The inner was ii. And the deepest was iii. That alone made it hard to read, but for a couple years some iii's and ii's were mixed up when getting values for arrays. So it was even harder to tell what it was supposed to do.
The inner loop also started at i-20. This was so he could look through and see if an email was already included from that query and skip it. But he didn't check the bounds, so the first 20 times through the outer loop, the inner loop would throw `undefined index -20` errors.
In order to fix all this I did an order by on the query, and kept a last email variable that I used for comparison. Pretty basic. This also lowered it to just one loop.
I talk about it on a regular basis with my coworkers and we all laugh about it. I also bring it up when upper management thinks they can code, because that ex developer is now an executive.
When defining a range, let's say from 1 to 3, I expect:
[1, 2, 3]
Yet most range functions I come across, e.g. lodash, will do:
=> [1, 2]
And their definition will say: "Creates an array of numbers ... progressing from start up to, but not including, end."
Yet why the fuck not including end? What don't I understand about the concept of a frigging range that you won't include the end?
The only thing I can come up with that's this is related to the array's-indexes-start with-0-thing and someone did not want to substract `-1` when preparing a for loop over an 10 items array with range(0,10), even though they do not want a range of 0 to 10, they want a range from 0 to 9. (And they should not use a for loop here to begin with but a foreach construct anyway.)
So the length of your array does not match the final index of your array.
Yet now we can have ranges with very weird steps, and now you always have to consider your proper maximum, leading to code like:
var start = 10;
var max = 50;
var step = 10;
_.range(start, max + step, step)
=> [10, 20, 30, 40, 50]
and during code review this would scream "bug!" in my face.
And it's not only lodash doing that, but also python and dart.
Except php. Php's range is inclusive. Good job php.4