DEV Community

Marcelloh
Marcelloh

Posted on • Edited on

Solve code complexity (in Go) Part 2

#go

spaghetti coding

Introduction

So I wrote the previous post and looked at a lot of software, because my linter pointed me at some interesting parts of software made by others. The linter looks at code the way a developer would look at it and judges the code according to that "knowledge". I have to say that I totally agree with the findings of my linter. Some code is so hard to read and, therefore, to understand.

Testing my linter in the real world

I did some testing of Go projects that got my attention. Downloaded those and let my linter point me to it's "wisdom". I sometimes took the liberty of passing that information to the project it reported about.

Some projects really understood what the "flaw" in their software was, and how they could improve from this knowledge.

Other people ask me to explain more about the simplification and how I would do it.

And there were also some who just found it annoying. My software works, so what?

This last group can't be saved, but for the others, please read on.

Advantage

Using this linter as soon as you finish writing a part of the code would be ideal, because it will give you some hints about the code complexity. Since the software was just made, you can easily refactor it to make it more simple and maintainable. This would be the real advantage.

What can you do?

There are some tricks that you can use to make software simpler.

If there is an if-statement with a lot of code inside, check if you can change it into an early-return.

If there is a loop with lots of code inside, isolate that code into another function.

If there is a switch-statement with cases that have a lot of code inside, isolate that code into another function.

Take a close look at nested if-statments, and nested loops. See if you can rewrite this in another way or isolate more into separate functions.

Did you know that your IDE might have a refactor option to easily isolate selected code into a new function? (I know Visual Studio Code has a way to extract code into a new function.)

Still testing

I made some changes in my linter because my opinion of what complex is, can be totally different from what others think. I now have a configuration in which you can set your own complexity boundries. To me, this is more than perfect, because perhaps you can read spaghetti-code and your colleagues can too.

I am still unemployed and while looking for a job, I can do some linting for others.

For now, before I make the tool available, it means that you can drop me a message (on here or on LinkedIn: see my profile) with the url of your git repository and I will get you your report.

Part 3

Top comments (0)