I’ve been interviewing candidates lately, which has made me think about everyday things in terms of screening/interviewing questions. Perhaps then a good question for an iOS developer is “How would you prevent a goto-fail situation?”.

Of course, “braces” comes up first, and compiler options may come up second, so let’s change that to “Aside from braces and compiler settings, how would you prevent a goto-fail situation?”.

Over the last few days, I’ve been reversing my role to think how I would answer that from an interviewer.  The idea that occurs to me the most boils down to “defensive coding” or “best practices and standards”. Now that’s way too vague.  As an interviewer I would ask for details.  I’m sure any practiced interviewer would.

For me, the biggest problem with the goto-fail code is the assumption of success until failure throughout the instructions. In critical code, it is better to assume failure until success is specifically reached. 

To illustrate:

The variable “err” is not initialized. While technically this is not a problem, it is not good practice if you assume it is possible that someone (now or in the future) can make a mistake. To assume failure, the variable must be set to something that means “failure”.  Then if a bug causes a premature return of the code, it will be a safe false-failure result instead of an unsafe false-success result.

The variable “err” is given the double-duty to hold results of intermediate steps and to hold overall results.  If there are 4 steps required to reach full success, then the overall result should not change from “fail” to “success” until the very last one is completed successfully.  If a later developer makes a mistake with an intermediate step, and jumps to the end, the result will be the safer “fail”.

Lastly, when execution arrives at “fail:”, the question “how did we get here?” cannot be answered. (Remember, the variable was not initialized.)

With a simple adjustment, the question can be answered:

Now the code cannot mistake a “goto fail” with a successful completion.

Assuming that this code will now give false-negatives (false failure), we can argue that people will notice that.  They will complain when their website does not work.  And they will notice the false-negative a lot faster than a large series of false successes.  (Hopefully someone will notice during development or testing, before customers see it.)