Peter Björklund

Peter Björklund

in Development

Funny story on debugging code

About 10 years ago I was asked to debug a process in a large Java application that bombed-out often with the famous and stress-inducing java.lang.NullPointerException.

The first I usually do when hunting errors in unfamiliar code are to identify the source of the error and check the commit log to get some history on it. The code in question had been through many, many iterations where the code had grown exponentially to do more and more diverse things. This is usually a bad sign, think of it as building a house of cards.

According to the commit log, people had tried to "fix" the problem. In some cases, they actually tried to catch the elusive NullPointerExceptions. OMG... 😂

Anyway, I found the method that was causing the problem, and when opening it up in my IDE I see a method with 500+ lines of code making all kinds of calls to resources here and there, and then it went into some endless nested if/else if/else checks 3 levels deep. The developer should get an award for getting the cyclomatic complexity that high, the thing was brutal. In the end, the method should return a boolean. Mmmkaay...

It took me almost a full day to go through it all, following each and every path through the code. After having created some tests and evaluated all the paths, checking for side-effects, etc. I concluded that the method could only return A) false or B) crash with a NullPointerException.

That's a lot of code for returning false I thought. After taking another sweep to confirm I was right I fixed the problem.

public boolean doSomeComplexStuff() {
  /* Removed 500 lines of I don't know what it was (see repo) */
  return false;
}

It seemed to do the trick, everyone seemed happy and the system worked as expected. So what did the method really do? I don't have a clue.. apparently no one else either 😂

What can we learn from this? Don't write 500 lines of code in a single method and keep the complexity down. Conditional branching is bad. Start nesting stuff and you will have a bad day or give someone else one.

Do you want to read more like this? Hit subscribe. It’s FREE!