Why I understand you are using ‘continue’ and why you shouldn’t

Recently I had to help out on a colleagues project, which I was not that familiar with.

First of all this ment to work the code and get a general understanding of what was happening. So after a while I found the spot where I had to put my changes. Implementation was done quickly enough and I was on my way testing.

First test didn’t give me anything. “Hmm.. this should work.. why am I getting no emails?”
Second test didn’t work the way I expected as well “Is my email sending broken?”
The third test was about my general ability of sending and receiving email. At least something was working the way I expected.

So it had to be the general function I was working at and naturally, revisiting the code brought the problem to light. My colleague used a rather cheeky way to abort the foreach loop, which prevented the function from ever reaching my newly implemented lines of code.

This is what I found up the lines:

foreach ($seatOfDataArray as $setOfData) {
  if (!array_key_exists($campaign->id, $telemarketingCampaigns)) {
  // Do something with $setOfData

  // Here was my code

It was pretty obvious what he was trying to achieve, but using continue was something I didn’t expect at all and wasn’t checking for when debugging my own code.

In my eyes using continue is always a doubled edged blade, especially when used in a prominent position. On the one hand it is of course a convenient way to simply abort a loop, on the other hand it is the easy way out. Why not define a condition, which can be used as a wrapper?

if (array_key_exists($campaign->id, $telemarketingCampaigns)) {
  // Do something with $setOfData

This way people, who are not aware of the easy way out above will not run into a trap when working in unknown territory. In addition it is alot more forward way of thinking, as the next person does not have to remodel the condition in his head to something which applies to what follows.

Using continue might be okay for prototyping or making something work initially, but it should never be the final solution.

It tends to produce unclean code, prevents a logical way of reading code and becomes hard to handle once someone else has to work with it.

Leave a Reply

Your email address will not be published. Required fields are marked *