21
teapot
2y

Wow i must have been brain dead when i wrote this code. Needed to exclude certain elements from response for the the list of objects.

for (obj : objects) {
If (obj.skipFromResponse()) {
break
}
add obj to response
}

I used break instead of continue at the if condition which meant it would break out of the loop at the first instance of condition being met.

This went through qa and has been in production for 4 weeks so how did this not break before. Well little did i know the list of objects was sorted and all the test data, qa data and everything so far in production coincidentally only had the last element with matching condition. This meant it returned everything correctly so far.

Today was the first time there was a situation where this caused incorrect output. Luckily as soon as I heard the description of the issue I remembered to check the merged PR and hung my head in shame for making such trivial error. I must have written way more complicated code without any problem but this made me embarrassed to even admit. 🤦‍♂️

Comments
  • 9
    Its when you relax you makes the simplest mistakes :)

    And if the input was always sorted this would be the most efficient so its not automatically wrong.

    This is a case where reversing the if would have made more sense as you would have avoided either break or continue and it would not be a question if you wanted to go over the whole list.

    And I know, many tools recommend this format for less indentation.

    But thats just a general recommendation and not always true :)
  • 0
    Did somebody say unit tests?
  • 1
    Break is a code smell, put the rest of the loop in the if to simplify your control flow.
  • 0
    @nibor Unit tests are only as good as the test data you feed them...
Add Comment