Krista's Coding Corner

09.02.2013

Spaghetti code

I hope you have read my previous post OR you know something about function block diagrams as it makes this post easier to understand :)

We often talk about "spaghetti code" meaning it is really messy with its functions. In ordinary code you can.t see connections and dependencies easily but with function blocks all that comes straight to your face.

Once me and another student made a huge mistake when we started building an automation system (it was just a course work in university, and I still can't understand how I ended up in that course but it has been one of the most useful things I have ever done). We really made it as wrongly as one can do. Worst thing was that the whole system was created to look like this:

You can easily see that when we tried to debug the system when it didn't work or worked in really mysterious ways, it became 'mission impossible' / 'lose your mind'. Luckily we realized quite fast that we should have built the system in smaller pieces (read: our system architecture was a mess as there was no system architecture). This is a very important lesson that unfortunately many haven't learnt.

If you can chop your program into smaller pieces: do it. It is so much easier to see if things work and what is the bad apple in your basket. Also if you have to repeat some parts again and again (meaning: you are able to use copy paste), there is something wrong in your program. Chop it. Never use copy-paste, only cut-and-paste!

Our final version of the automation system worked like a dream and it was able to fix all sorts of problems by itself. We could have never done so fine system, if the debugging hadn't come easier. And if the structure hadn't been flexible, so that every time we invented a new type of a possible problem (like: user put's a screwdriver to sensor with no reason), we wouldn't have been able to just add that scene to code and give it steps how to fix things WITHOUT messing the normal functionality of the system.

Now, just chopping things into smaller pieces doesn't make sure you don't have spaghetti code. You also need good, reasonable and clear architecture. Your code can't jump back and forth, it has to have clear flow. See more from: post 32 and next post.

And remember that maybe later you want to add things to your code: this shouldn't make you rewrite everything.

blog comments powered by Disqus