Hacker News new | ask | show | jobs
by nialo 3184 days ago
Asking honestly because I would like to know: What is wrong with writing a state machine using gotos? Assuming that one is solving a problem that definitely needs a state machine for some reason.
4 comments

Nothing wrong with goto, as long as it's clear.

Many programmers treat 'goto' the same way that we treat radioactive waste, but they don't know why. Perhaps it is a holdover from courses with teachers who automatically graded 'fail' on programs that used a goto. Perhaps the programmers have only heard that gotos were bad.

Sometimes 'goto' is the correct answer. For state machines it can be an pretty efficient technique. For "ordinary" code it is sometimes the best way out of a situation (e.g., busting out of a deeply nested set of loops).

The "Goto considered harmful" movement came out of the 1970s, when GOTO was used all the time and the normal state for a big project was abject spaghetti. I think we can all agree that was a very bad thing. But the utter avoidance of goto is an overreaction that seems to be based on unreasoning fear, or toxic peer pressure.

>busting out of a deeply nested set of loops

so, goto is efficient at escaping inefficiently structured code? That doesn't make it really efficient. I mean there's a reasonable rule of thumb: don't indent the code too deep. Because what you are talking about is one kind of spaghetti, the kind cut into digestable chunks. The interleaving of active and inactive blocks leads to unreadable code sooner or later.

> What is wrong with writing a state machine using gotos?

Nothing. But the thing they want to do -- altering the datastructure on the fly -- is not the best way to solve the problem.

I would solve this by writing two functions: one that creates an array from a binary tree, and one that creates a doubly-linked list from an array.

Would this use up more RAM and take longer to run? Yes

Would the code be easier to understand (and therefore more bug-free)? Yes

It's "barbaric", kinda like eating with your hands.

Of course this type of dogmatism gives us FP gems akin to [eating] a piece of Sushi with a steak knife.

Gotos are generally considered a bad idea in high-level programming.

http://www.u.arizona.edu/~rubinson/copyright_violations/Go_T...

This is lazy thinking, the gotos described in that essay can jump anywhere in the program while modern gotos are limited to the function scope and have various warnings about initialization order and whatnot.

All the arguments it makes no longer apply but people still quote the snappy headline.

That essay does make an excellent argument against programming with many tiny functions though, as those do cause the execution cursor to jump all over the source code document.

It seems to me that a substantial fraction of the people who quote that paper, assuming they have even read it, have failed to think critically about it.