Skip to main content

Spaghetti Code Considered Harmful

To chefs and epicureans, spaghetti is a good thing-- it's inexpensive, easy to make, and very versatile. But spaghetti isn't so appetizing to a programmer. The phrase "spaghetti code" is an all-too-common pejorative we programmers use to describe horrible code, whether it's difficult to understand, poorly organized, or just plain long-winded. And there-in lays the problem. What really constitutes spaghetti code is subjective; I've yet to hear a concrete definition or standard metric that measures it.

I've seen PHP code that amounts to nothing more than a giant switch construct... a hundred lines here to handle this condition over here, another hundred or so lines in the branch for that condition over there, maybe a dozen conditions... you get the idea. But such code isn't necessarily spaghetti. What's wrong with it is not that it's unreadable, I would argue, but rather there is a lack of encapsulation. There's a greater chance of inadvertently modifying the wrong variable 800 lines down in some unknown branch, but scoping isn't spaghetti. The code may otherwise be beautifully formatted with the coding standard du jour, and the logic might be crystal clear.

I've also seen OOP code that has been so meticulously refactored that it would bring a tear of joy to just about any DRY-advocate's eye, but that doesn't always mean the code is well organized or easy to follow. It can be frustrating to trace through deep inheritance chains without the help of a modern IDE with project support. IDEs are tools that should help make working with code easier, not be a requirement to navigate what is essentially a set of text files. New professionals coming out of college now with an OOP perspective would be comfortable with such code. They view the same procedural code an old-time C programmer would be comfortable with as messy, unorganized, sloppy spaghetti.

An informal poll I took asked a handful of developers to try to explain what is spaghetti code. They all agreed that it was a term used to describe bad code, but everyone has his or her own opinion as to what aspects would make them label it spaghetti:
  • Spaghetti code is code that is written quickly and doesn't follow the accepted standard.
  • Spaghetti code is any code that uses goto.
  • Spaghetti code is code written by a beginner who's learning to program in Basic.
  • Spaghetti code is like spaghetti in that after you've digested it you are fatigued.
It's trivial to find code samples that relegate such metrics as mere preference, because each one relies on a subjective perception of quality.

The best response I received was from a friend and former co-worker, Sean H. "Spaghetti code is what we call other people's code when we think it's a pile of blackened shit that's baked in the sun and has flies swarming about it but we still want to be polite." Spaghetti code really has nothing to do with code, but rather how we choose to interact with one another. Lacking a proper definition but carrying a negative connotation, spaghetti is just complaining about other people's work which is not beneficial to ourselves or to the quality of the code we produce/maintain.

Some programmers are very protective of the code they write and they can react in a variety of ways to people who call their work spaghetti. Depending on their personality, in an extreme case they may view such comments as a personal attack and become overtly confrontational. Few people like to be challenged on their way of doing something. In a more subtle case, the programmer may begin to resent others. He feels misunderstood and begins to draw inward, subconsciously severing communication channels.

But besides negatively affecting others, our complaining about spaghetti code hurts ourselves too. It's easier to motivate ourselves when tasked with fixing a bug when we're not dreading having to trudge through spaghetti. When we label code as spaghetti code, we are actually creating roadblocks that hamper ourselves and artificially increase the difficulty of the task at hand. A better perspective to have is that we have been given the opportunity to use our skills to fix something and to make it better. Constant complaining only reinforces the wrong attitude and makes it easier to become disillusion with our craft; negativity "sucks the life out of you" and doesn't serve to create a better work environment.

It's almost always easier to complain and set oneself up for failure rather than success. Should I stop harping on Java? Probably. Should I not let my skin crawl every time I run into Zend Framework? Maybe. Though I consider myself successful, how much more successful could I be if I didn't put up mental blocks for myself over what amounts to other people's preference? I have no idea. Old habits die hard, but it's a worthy goal to strive for to stop alienating others and making life difficult for myself by complaining about spaghetti code. Feel free to join me in doing so.

Comments

  1. I myself write Lasagna code. That's simply spaghetti code that's multi-layered!!!

    ReplyDelete
  2. For quick demonstrative prototypes or less complex tasks in straightforward environments there are no reasons for you not coding spaghetti style.

    But the more complex an application becomes, the more you have to regard advanced techniques to master daily business tasks.

    I do usually develop in major sized php projects. One aspect is that long-running projects often suffer of short-sighted architecture, technical challenges and a disparity of programming skills. So I invented a system where I can combine spagehtti, lasagna or ravioli code written in different styles.

    ReplyDelete
  3. There's a common lingo here, the people who answered your poll just aren't familiar with it. :) http://en.wikipedia.org/wiki/Spaghetti_code

    "...code that has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other "unstructured" branching constructs. It is named such because program flow tends to look like a bowl of spaghetti, i.e. twisted and tangled."

    ReplyDelete
  4. I can understand the whole "be positive" approach, however, I think the problem with spaghetti code is the effect of having to deal with it on a daily basis. This effect slowly breaks down the morale of any developer, even hardened veterans. It essentially cripples a development team/department.

    Some applications, even on an enterprise level, have entire components which were written years before you, and still play a major part in the application stack. This means a rewrite, even partially, is a no-no due to the many reasons management will be more than happy to give you.

    Unfortunately, legacy is a reality, the problem is that its not always taken into account in the planning. The common answer you get is: "a rewrite doesn't generate profits" or "refactoring code doesn't help our clients", when the reality is that spaghetti code can single-handedly destroy your team, your product, and finally, your company.

    ReplyDelete
  5. Responding to Anonymous at comment #2 — my experience, both as a developer and mentor in a couple of dozen different languages, is that it's a mindset thing. Spaghetti code is, almost always, written in one long conceptual flow, without pause to reflect and refactor. This long movement continues until it's either done or too brittle to continue, and then when someone tries to continue doing anything with it later, they discover that it's congealed into a unitary mess.

    Long, long ago, people started realising that it made better code if you wrote as little as possible, tested it, verified that it did what you thought it did as cleanly as it possibly could (after a few refactorings), and then wrote the next bit. Today, that's called "agile;" back when I learned programming in the Paleolithic, it was called "incremental development."

    Nobody can maintain the same intensity of concentration for extended periods of time, repeatedly. Technology and/or biology, in one form or another, intervene. Structuring how you write code to take advantage of that, rather than attempting to fight against it, is how the best code I've ever seen has been written. In any language, on any platform.

    You don't have to code Java to be agile; I've been on teams that used Agile Manifesto-compliant systems in languages most JavaSchools™ ex-inmates have never touched: COBOL, FORTRAN, Lisp, APL; the list goes on.

    But whatever language you're using, whatever you're trying to develop, once the light-bulb goes on and you "get" the (to you) New Way of doing things, it becomes far too painful to go back; like "building a mnemonic memory circuit using stone knives and bearskins," to quote a character I'm sure is familiar to most who read this. It may be possible, at least in theory, if you're sufficiently talented, diligent, creative — and lucky.

    Just don't bet my paycheque on it.

    ReplyDelete

Post a Comment

Popular posts from this blog

Composing Music with PHP

I’m not an expert on probability theory, artificial intelligence, and machine learning. And even my Music 201 class from years ago has been long forgotten. But if you’ll indulge me for the next 10 minutes, I think you’ll find that even just a little knowledge can yield impressive results if creatively woven together. I’d like to share with you how to teach PHP to compose music. Here’s an example: You’re looking at a melody generated by PHP. It’s not the most memorable, but it’s not unpleasant either. And surprisingly, the code to generate such sequences is rather brief. So what’s going on? The script calculates a probability map of melodic intervals and applies a Markov process to generate a new sequence. In friendlier terms, musical data is analyzed by a script to learn which intervals make up pleasing melodies. It then creates a new composition by selecting pitches based on the possibilities it’s observed. . Standing on Shoulders Composition doesn’t happen in a vacuum. Bach wa

Learning Prolog

I'm not quite sure exactly I was searching for, but somehow I serendipitously stumbled upon the site learnprolognow.org a few months ago. It's the home for an introductory Prolog programming course. Logic programming offers an interesting way to think about your problems; I've been doing so much procedural and object-oriented programming in the past decade that it really took effort to think at a higher level! I found the most interesting features to be definite clause grammars (DCG), and unification. Difference lists are very powerful and Prolog's DCG syntax makes it easy to work with them. Specifying a grammar such as: s(s(NP,VP)) --> np(NP,X,Y,subject), vp(VP,X,Y). np(np(DET,NBAR,PP),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y), pp(PP). np(np(DET,NBAR),X,Y,_) --> det(DET,X), nbar(NBAR,X,Y). np(np(PRO),X,Y,Z) --> pro(PRO,X,Y,Z). vp(vp(V),X,Y) --> v(V,X,Y). vp(vp(V,NP),X,Y) --> v(V,X,Y), np(NP,_,_,object). nbar(nbar(JP),X,3) --> jp(JP,X). pp(pp(PREP,N

What's Wrong with OOP

Proponents of Object Oriented Programming feel the paradigm yields code that is better organized, easier to understand and maintain, and reusable. They view procedural programming code as unwieldy spaghetti and embrace OO-centric design patterns as the "right way" to do things. They argue objects are easier to grasp because they model how we view the world. If the popularity of languages like Java and C# is any indication, they may be right. But after almost 20 years of OOP in the mainstream, there's still a large portion of programmers who resist it. If objects truly model the way people think of things in the real world, then why do people have a hard time understanding and working in OOP? I suspect the problem might be the focus on objects instead of actions. If I may quote from Steve Yegge's Execution in the Kingdom of Nouns : Verbs in Javaland are responsible for all the work, but as they are held in contempt by all, no Verb is ever permitted to wander about