Code Smell 280 - Spaghetti Code
This article is dedicated to the late Thomas E. Kurtz, one of BASIC's creators, as it was the first programming language I learned.
TL;DR: GOTO statements create confusing and unmaintainable code
Problems
- Logic becomes unclear
- Debugging gets harder
- Flow jumps erratically
- Code lacks structure
- Maintenance becomes difficult
Solutions
- Use structured programming
- Replace with loops
- Simplify control flow
- Avoid unnecessary jumps
Context
Spaghetti describes code that is poorly structured and difficult to understand. It often involves deeply nested loops, excessive use of goto statements, and complex control flow.
When you overuse GOTO statements, your program becomes a tangled mess of uncontrolled jumps.
This was common in the 70s when BASIC encouraged GOTO for flow control. While it can solve simple problems quickly, GOTO leads to spaghetti code that’s nearly impossible to debug or extend.
Spaghetti Code << Structured Programming << Object-Oriented Programming << Machine Learning Programming
Sample Code
Wrong
0 REM Request a Zero
10 INPUT "Enter a number: ", N
20 IF N = 0 THEN GOTO 50
30 PRINT "Number is non-zero"
40 GOTO 10
50 PRINT "Goodbye"
60 END
Right
10 DO
20 INPUT "Enter a number: ", N
30 IF N <> 0 THEN PRINT "Number is non-zero"
40 LOOP UNTIL N = 0
50 PRINT "Goodbye"
60 END
Detection
[X] Automatic
You can detect this smell by scanning for frequent GOTO usage, especially when they jump between unrelated code sections.
Look for logical breaks caused by excessive jumping and ask if structured control flow can replace them.
Tags
- Coupling
Level
[X] Beginner
AI Generation
AI generators can include GOTO when mimicking older coding styles.
They might use it for simplicity without considering modern best practices.
AI Detection
You can instruct AI to replace GOTO with loops or structured constructs like IF-ELSE or WHILE.
Try Them!
Remember: AI Assistants make lots of mistakes
Without Proper Instructions | With Specific Instructions |
ChatGPT | ChatGPT |
Claude | Claude |
Perplexity | Perplexity |
Copilot | Copilot |
Gemini | Gemini |
Conclusion
Overusing GOTO creates chaotic and unmanageable code.
Replace it with structured programming techniques to improve readability and maintainability.
Relations
More Info
Disclaimer
Code Smells are my opinion.
Credits
Photo by Sofia Ciravegna on Unsplash
Spaghetti code is a program with its logic tangled like spaghetti. Avoid the tangles, and you simplify your life.
Martin Fowler
This article is part of the CodeSmell Series.
Subscribe to my newsletter
Read articles from Maxi Contieri directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Maxi Contieri
Maxi Contieri
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.