29
Aug '14

GOTO

I can’t believe it. I’ve just been convinced of a valid use-case for the ‘goto’ statement. I never ever thought this could happen, and admittedly it’s only really valid in procedural languages that don’t have built-in error or exception generation/handling. Yet still, for those PHP1 and POP11 programmers out there, here it is.
The valid use-case is emulating exception generation in a procedural environment. If ‘goto’ is used to trigger a terminal action as an exception within procedural code it actually kinda makes sense. The key point is the action being terminal (i.e. the last thing that happens before you exit) and there being no better built-in way of doing it.
From wherever you are in your code, if something goes wrong and you want to throw an exception then you are effectively jumping out of the normal flow, spitting out your exception and exiting. ‘Goto’ can achieve this within procedural code reasonable well and safely.

function thisIsMyFunction($this_is_a_var = false) {
     if($this_is_a_var) {
          //Happy path
     }
     else {
          goto exception;
     }
}

exception:
echo 'Well something went wrong there!';
exit();

Obviously that example was in PHP which is no longer a procedural language, but you get the idea.

I still haven’t found any good reason to use ‘eval’ though…

Leave a Reply