DEV Community

Cover image for Code Smell 100 - GoTo
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 100 - GoTo

GOTO was considered harmful 50 years ago

TL;DR: Don't ever use GoTo.

Problems

  • Readability

  • Hard to follow code

Solutions

  1. Replace GOTO with structured code

  2. Use exceptions

Context

I started programming in Basic.

GOTO was heavily abused there.

I had to learn structured programming from scratch in Rehab mode.

Sample Code

Wrong

for x < 0 {
    if x > -1e-09 {
      goto small
    }
    z = z / x
    x = x + 1
  }
  for x < 2 {
    if x < 1e-09 {
      goto small
    }
    z = z / x
    x = x + 1
  }

  if x == 2 {
    return z
  }

  x = x - 2
  p = (((((x*_gamP[0]+_gamP[1])*x+_gamP[2])*x+_gamP[3])*x+_gamP[4])*x+_gamP[5])*x + _gamP[6]
  q = ((((((x*_gamQ[0]+_gamQ[1])*x+_gamQ[2])*x+_gamQ[3])*x+_gamQ[4])*x+_gamQ[5])*x+_gamQ[6])*x + _gamQ[7]
  return z * p / q

small:
  if x == 0 {
    return Inf(1)
  }
  return z / ((1 + Euler*x) * x)
}
Enter fullscreen mode Exit fullscreen mode

Right

for x < 0 {
    if x > -1e-09 {
      return small(x, z)
    }
    z = z / x
    x = x + 1
  }
  for x < 2 {
    if x < 1e-09 {
      return small(x, z)
    }
    z = z / x
    x = x + 1
  }

  if x == 2 {
    return z
  }

  x = x - 2
  p = (((((x*_gamP[0]+_gamP[1])*x+_gamP[2])*x+_gamP[3])*x+_gamP[4])*x+_gamP[5])*x + _gamP[6]
  q = ((((((x*_gamQ[0]+_gamQ[1])*x+_gamQ[2])*x+_gamQ[3])*x+_gamQ[4])*x+_gamQ[5])*x+_gamQ[6])*x + _gamQ[7]
  return z * p / q

small(x, z){
  if x == 0 {
     return Inf(1)
   }
   return z / ((1 + Euler*x) * x)
 }
}
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

In languages supporting GOTO, our linters can warn us against its usage.

Tags

  • Readability

Conclusion

We acknowledged GOTO problems a few decades ago.

The problem is still present in modern languages.

Most programmers luckily avoid GOTO sentence. Next goal will be to consider harmful null usage.

Joke

Courtesy XKCD

Relations

More Info

Credits

Photo by Jens Johnsson on Unsplash


It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.

Edsger Dijkstra


This article is part of the CodeSmell Series.

Top comments (0)