C# Spaghetti Code

The C# programming language

Spaghetti code is not pasta. The term spaghetti code is used to mean code that is hard to follow because of how it uses loops, control variables or jump statements. Typically, spaghetti code can be rewritten to be clearer with the use of methods and straightforward loops.

This C# article describes spaghetti code and provides some examples.

Example

Note

This example shows how the goto statement can be used to create a looping construct. Four labels, SWITCH, MULTIPLY3, ADD1, and SUBTRACT1 are used and several goto statements are used throughout the program. It would be much clearer to loop over the selection statement instead of using goto statements to jump to it.

Program with spaghetti code [C#]

using System;

class Program
{
    static void Main()
    {
	int value = 0;
    SWITCH:
	switch (value)
	{
	    case 0: goto ADD1;
	    case 1: goto MULTIPLY3;
	    default: goto SUBTRACT1;
	}
    MULTIPLY3:
	value *= 3;
	goto SWITCH;
    ADD1:
	value += 1;
	goto SWITCH;
    SUBTRACT1:
	value -= 1;
	Console.WriteLine(value);
    }
}

Output

2

Program with structured code [C#]

using System;

class Program
{
    static void Main()
    {
	int value = 0;
	while (true)
	{
	    if (value == 0)
	    {
		value += 1;
		continue;
	    }
	    if (value == 1)
	    {
		value *= 3;
		continue;
	    }
	    value -= 1;
	    break;
	}
	Console.WriteLine(value);
    }
}

Output

2

Intermediate representation

What I find most interesting about spaghetti code is its relation to the intermediate representations used in compilers. A spaghetti version of a program, such as the one above that uses GOTO statements, is another representation of a structured program, such as the one with the while(true) loop.

This section provides information

A compiler would be able to transform one to the other. And, if you are trying to represent a program as a series of low-level instructions, the spaghetti version might be closer to your goal then the high-level version. This means that spaghetti code can reflect more closely what is actually being done at a low level on the machine.

With intermediate representations, we can transform programs in a way that they are functionally equivalent but dramatically different in appearance and structure. Spaghetti code, then, is the worst kind of representation in that it does not fit the level at which a language is intended to be used: it is low-level in places where high-level would be better.

Summary

We considered spaghetti code in the C# language and related the concept of intermediate representations. Spaghetti code looks different from well-structured code, but can more closely reflect what happens at a lower level of the machine. However, this defeats the whole purpose of high-level languages.

Loop Constructs
.NET