Refactor The Spaghetti

Sean Coates
2 min readDec 10, 2017

--

Learn techniques to replace messy code.

When a section of code looks like a hot mess, it can be very difficult to understand exactly what it is doing. The intent of the code gets muddled, and it becomes easy to miss the fine details and particulars. It’s also likely that the test coverage is insufficient for the task.

Your goal should be to unwind this spaghetti code into a collection of several small methods, each with its own unit tests. There are several techniques one should investigate when going about this kind of effort.

The first and most important is to keep methods short, moving logic to other methods. At first, it may seem inane to replace three lines of logic with one method call, but if those three lines belong together, then go ahead do it. Every little bit helps. Repeating this process throughout the code will unwind a lot of spaghetti.

Sometimes nested if statements can be replaced with boolean logic. This particularly true when all that is inside an if block is another if statement with its own block.

Learn the proper use of map, reduce, and array walk routines. These can simplify iterations. You should also learn to build iterators, so the complexity of the iteration can be hidden in its own procedure. This is also handy if you have nested iterations, like when processing data in a multi-dimensional array.

Replace nested if statements with a series of if statements where possible. These can, in turn, be replaced with methods. When there are if statements that are acting as filters, one can sometimes replace them by using request objects.

Read books on refactoring and learn more advanced techniques. Ultimately, you should never have any spaghetti code. When you’re done, the code should be obvious and easy to understand by the casual reader.

--

--

Sean Coates

Occasional posts from @fooyay about software engineering, crypto, finance, and more. https://fooyay.com for current content.