How do I distinguish between a “GOTO” version of an IF block and a “Structured” version of an IF block?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/354607

  •  17-01-2021
  •  | 
  •  

Question

So I came across an old blog post from Robert Martin (Uncle Bob) that talks about how the Structured Programming discipline convinced programmers to take the GOTO statement out of their code, even when its only implicit like in this example that he gave:

if (a>10)
  b++;
else
  b--;

He said that was bad practice because it basically would correlate to this code if written in FORTRAN:

    IF (A-10) 20,20,30
20  B = B - 1
    GOTO 40
30  B = B + 1
40  ...

To me, that makes sense. An If block essentially acts like a GOTO statement under the hood so why use it. (Of course, in the back of my mind, I'm thinking there's no way to get around some kind of JUMP instruction in the underlying assembly language, which is basically a GOTO statement, but I ignored that thought and moved on.)

But then he said:

you could restrict your program to three different control structures: Sequence, Selection, and Iteration

and that with a Selection structure, you could write code like this:

if (someBooleanValue())
   doThisStep();
else
   doOtherStep();

That's supposed to be a better version of an If block than the GOTO version I mentioned above because it used a Selection structure. However, I don't really see the difference between them. What is the fundamental difference?

The only thing I can figure is that is has something to do with what he said here:

Dijkstra's argument was that a structured program can be easily analyzed because the state of the system at any line of code, depends only on the boolean values being tested by selection and iteration, and the list of calling procedures on the stack.

Somehow it seems like there is a deeper principle here that I'm missing. I get that you can keep track of the state of a program using boolean variables but what does that have to do with these two If blocks?

Was it helpful?

Solution

What is the fundamental difference?

There isn't one.

The reason your friend's argument falls apart is because any if-else can be rewritten using a goto. In fact, at the processor level, every branch instruction (including the conditional ones) is a goto.

Structured programming is the act of using a structured programming language to write structured code, not musing about what the equivalent code in another language is, or what is happening under the language's hood.

Licensed under: CC-BY-SA with attribution
scroll top