What is spaghetti code?

Asked

Viewed 3,803 times

52

When reading about software architecture on the web, sometimes the term is used "spaghetti code", referring to something that should be avoided.

But I could never understand clearly what "spaghetti code" means.

  • 5

    +1. I find this kind of question very important and look forward to seeing good answers :) Beforehand, this is relevant: http://en.wikipedia.org/wiki/Spaghetti_code

  • 3

    @Marcelobonifazio I was surprised, because I work with programming for about 10 years and had never heard of lasagna code and ravioli code (seriously, look there!). I’ll see if I can find anything on fusilli code because it’s my favorite XD pasta

  • Even before the OO paradigm the paradigm of Structured Programming. It turns out that the "young" have already learned in this paradigm and do not imagine what was the mess of programming with GOTO, GOSUB, JPZ, etc.

4 answers

59

Ensō, o símbolo da iluminação, força, elegância, o universo e o vazio

So said the Master Programmer: A well-written program is its own paradise; a poorly written program is its own hell.


The code Spaghetti is the antithesis of the code Zen.

It is the process noise tending to infinity when expressed in code.

It is the preferred solution of beginner palates, but not refined; it kills hunger, but does not bring satisfaction.

The master programmer, on the other hand, prefers his clean and lean code. He strokes the processor instead of torturing it.

The code Zen is universal; with one look you know exactly what it does.
The code Spaghetti is cryptic. It cannot be intuited. You need to map it.

The code Zen is succinct. In a few lines it covers the whole process.
The code Spaghetti is repeated rhythmically, but is pretentious and makes misuse of time.

The code Zen facilitates and embraces growth.
The code Spaghetti makes maintenance difficult, costly and slow.

The code Zen is like water, adapting to new forms effortlessly.
The code Spaghetti, when fixed at one point, creates bugs in others.

The code Zen is a poem.
The Code Spaghetti is the three hour speech of the financial director.

Sources (in English):
   - The Tao of Programming
   - Fundamental Laws of the Spaghetti Code
   - Ensō

With collaborations of @brasofilo. Thank you!

  • 1

    Does this come from some book? I need to know which one!

  • 4

    @Renan is not from any book but is inspired by various texts. = ) I added the links, good avail!

  • 2

    The last "stanza" won me.

  • 1

    I do not agree that that is the accepted answer. The idea behind it is good, but it is expressed in a way too subjective in many places and for me it would serve more as a complement to a reply like @Jay’s, based on Wikipedia. Just my two cents. Even so I approve the fact that it is going a little further and demonstrating drawbacks of the code spaghetti.

  • 2

    @Piovezan I understand his point, and the programmer within me could not agree more - the reason for my upvote for Jay and Ademir. When I started writing the first draft of my response I went in this direction; but, because of the amount of existing languages, and since the goal of the answer was to be agnostic about language, I found myself writing a Spaghetti response - long and hard to read. And, while certain poetic freedoms were taken, the goal of demonstrating clarity, simplicity and readability (as opposed to the focus of the OP) were maintained.

  • 5

    Sometimes subjectivity can be more concise than the most Cartesian explanation.

  • 1

    That answer was brilliant. And I agree with @Ciganomorrisonmendez.

Show 2 more comments

25


It is a code with flow complexity, usually in a constant line of execution, where it mixes execution jumps using unconditional deviation structures, such as the GOTO, END, etc..

An example with spaghetti code in BASIC:

10 i = 0
20 i = i + 1
30 PRINT i; " squared = "; i * i
40 IF i >= 10 THEN GOTO 60
50 GOTO 20
60 PRINT "Program Completed."
70 END

That could be implemented in a better structured way:

10 FOR i = 1 TO 10
20     PRINT i; " squared = "; i * i
30 NEXT i
40 PRINT "Program Completed."
50 END

It is also used as a term for mixing technologies when developing with scripting languages, such as in PHP+HTML. Understand that PHP is used as a template on MVC architectures of systems where classes that generate the output (View) need to write pure HTML and insert dynamic data into their generation. The term spaghetti code here would be used when the logic of the PHP program is inserted along with the user interface output.

An example in PHP + HTML

<!DOCTYPE html>
<html>
<head><title>Macaronic Code</title></head>
<body>
    <?php
        $ip = $_SERVER['REMOTE_ADDR'];
        $dbh = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
        $statement = $dbh->query("SELECT lastlog FROM logins WHERE ip = '$ip'");
        $row = $statement->fetch(PDO::FETCH_ASSOC);
        $dbh->query("INSERT INTO logins VALUES ('$ip', CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE lastlog = CURRENT_TIMESTAMP");
    ?>
    <p>Hello, <?php print $ip; ?>.</p>
    <script>
        var lastlog = "<?php print $row['lastlog']?>";
        if (lastlog > "") alert("You last visited "+lastlog);
        else alert("You've never been here before.");
    </script>
</body>
</html>

This code would have a better architecture if the connection logic was in a class or connection function, separate from HTML. Database query logic also in a class or function. And there was a flow control routine that called output generation, passing the data it should use, perhaps in the format of an array.

And then the HTML part would only use PHP as template according to the example below:

<!DOCTYPE html>
<html>
<head><title>Better Code</title></head>
<body>
    <p>Hello, <?php echo $data['ip']; ?>.</p>
    <script>
        var lastlog = "<?php echo $data['lastlog']?>";
        if (lastlog > "") alert("You last visited "+lastlog);
        else alert("You've never been here before.");
    </script>
</body>
</html>

In the above example we could still improve this code by separating the Javascript part and inserting as an external file non-intrusively.

The Wikipedia entry in English also describes the code lasagna, ravioli and macaroni.

The article Spaguetti Code describes techniques, strategies for refactoring a spaghetti code.

To understand some of the other concepts cited:

Excuse the references in English, but they present a better content than the Portuguese I found.

18

Spaghetti code is code that has complicated control flow, abusing mechanisms such as exceptions, unconditional deviations (GOTO), and similar constructions. This name is given because the code flowchart of this type has many lines crossing and going everywhere, remembering in fact a spaghetti noodle.

Spaghetti code is common practice in BASIC, for example, and the language Pascal emerged precisely to encourage the use of structured programming, avoiding the "control flow mess".

There’s a wikipedia entry about this.

  • 4

    I think spaghetti is universal. Programming Esperanto. I’ve seen it in Lingo, Actionscript, Javascript and PHP. I’m sure my first steps on Pascal were spaghetti as well, but unfortunately I no longer have historical records...

  • 1

    @Brasofilo I’m sorry you programmed in Lingo :) Curiosity: what do you use today in place of the Director? I do many standalone applications in this style, and every hour I have used a different technology.

  • 1

    @bfavaretto, I don’t resent Lingo, I thought it was funny ;) Turned DVD Studio Pro for video presentation and Flash for web interactivity. Some crazy DVD browsing, and I even started making a hybrid dvd video/mac/win, but it didn’t go forward. Then everything became web, with Wordpress/jQuery replacing Flash.

  • @brasofilo I also mainly use web technologies nowadays (HTML5 + JS), but often need it to run offline, on kiosks or Node-Webkit).

2

Spagheti code refers to code whose control flow is confused and interlaced like spaghetti. This way, each line of code can be referencing almost any variable anywhere and keeping the code becomes virtually impossible, because the risk of introducing errors elsewhere is too great. This term is widely used in the context of programming that uses the Goto statement.

This is different from noodle code, which can be defined as a code that uses a mixture of programming languages in a single document. Thus, to understand a Macaroni code it is necessary to have knowledge of most of the languages used in this code.

The example below is a macaroni code, which mixes the HTML, PHP, SQL and Javascript languages into a single document.

<!DOCTYPE html>
<html>
<head><title>Macaronic Code</title></head>
<body>
    <?php
        $ip = $_SERVER['REMOTE_ADDR'];
        $dbh = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
        $statement = $dbh->query("SELECT lastlog FROM logins WHERE ip = '$ip'");
        $row = $statement->fetch(PDO::FETCH_ASSOC);
        $dbh->query("INSERT INTO logins VALUES ('$ip', CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE lastlog = CURRENT_TIMESTAMP");
    ?>
    <p>Hello, <?php print $ip; ?>.</p>
    <script>
        var lastlog = "<?php print $row['lastlog']?>";
        if (lastlog > "") alert("You last visited "+lastlog);
        else alert("You've never been here before.");
    </script>
</body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.