2009-09-21

How to eat spaghetti (code)

I'm thinking about dinner so the subject has a culinary style.

I have spent some time fighting with spaghetti code that grown from adding more and more conditional strands to initial prototype of application framework.

Before major version release of middle size production system I had to add a new feature to the biggest important process. Not so big change - it looked simple. It just involved doubling of some model objects and making two separate subprocesses. After alternating main flow, many side effects occurred, caused by intertwined logic and persistence. I had to do some clean up, cut off tangled strands, standardize conditional flows and reduce code. The results still weren't valid - at least I have found "single point of failure". Because of time constraints I had to fix it with block of ugly code. The project needs change in the process structure to adapt new features in more seamless way.

When you meet that kind of "spaghetti code" there are two known ways of dealing with it:
- pull one strand at a time - clear one flow path - repeat until structure is simple enough
- eat it all at once - analyze requirements and used implementation and rewrite it from start

Reduce structure, simplify, refactor and do not let the code grow into spaghetti again. It will ruin maintainability and extendability of software project in future.

2 comments:

Anonymous said...

I am dealing with a spaghetti code now. I am asked to modify a reporting tool. The main problem is adding a new logic to an bizarre/inconsistent code that span 3 or 4 languages across multiples files with no structure at all. I proposed to decompose this code into smaller pieces and use a bottom-up approach. The other option is to use try/error method which is inefficient but no one is really paying attention, just fix it.

Tomasz Worona said...

That reminds me one of the "horror code" I have to maintain in an old ASP web application. The hardest piece was one above 100kB asp file (there were few more), containing intertwined pieces of servers side and client code written in both VBScript and JavaScript. Even with good syntax coloring it wasn't easy to get it.
Solution was rewrite from scratch.
"Thanks" to lack of DRY principle, there was no code reuse and no relations with other modules. So it wasn't example of spaghetti code, but gave good headache too.
That experience gave me also long remembered tip: reduce code clutter.