Many people accused me recently for just mentioning a single word - "goto".
It makes me wonder, why it is considered such a nasty word.
I am aware of several previous discussions on the topic, but it doesn't convince me - some of the answers just says "it's bad" not even trying to explain and some bring reasons, irrelevant for scripting languages like PHP, IMO.
Anyway, I am going to ask a very particular question:
Let's compare goto
and throw
statements.
Both, in my opinion, do the same thing: avoiding execution of some portion of code based on some condition.
If so - do throw
have same disadvantages as goto? (if any)?
If not - whit is the difference then.
Anyone experienced enough, who can tell the fundamental, conceptual difference between code structures of the two following code snippets?
Regarding these very code snippets, not "in theory" or "in general" or "here is a nice XKCD comic!".
Why the first one considered to be brilliant and latter one considered to be deadliest of sins?
#$a=1;
#$b=2;
/* SNIPPET #1 */
try {
if (!isset($a)) {
throw new Exception('$a is not set');
}
if (!isset($b)) {
throw new Exception('$b is not set');
}
echo '$a + $b = '.($a + $b)."<br>\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "<br>\n";
}
/* SNIPPET #2 */
if (!isset($a)) {
$message = '$a is not set';
goto end;
}
if (!isset($b)) {
$message = '$b is not set';
goto end;
}
echo '$a + $b = '.($a + $b)."<br>\n";
end:
if (!empty($message)) {
echo 'Caught exception: ', $message, "<br>\n";
}
Ben atış daha güçlü ve esnek olduğunu farkında olduğumu unutmayın in making spaghetti. Benim için asıl fark yapmaz. Bu kullanım meselesi değil, bir kavramdır.
EDIT
I've been told by many people that first example should be newer used.
Reason: Exceptions should be used to handle errors only, not to implement business logic.
It looks sensible.
Bu nedenle, tek yolu gereksiz kod yürütme durdurmak için sol olduğunu Goto (aynı mesele ama uygulamak zordur böyle iken, dönüş vb gibi bazı vekilden, söz değil)?