1

I had this crazy initialisation --

documentList = new ArrayList<Map<String,Integer>>();

which I intended to store a new map everytime in a loop but unfortunately put itself inside the loop. And you know the havoc.

How do you detect such mistakes? I might be looking for suggestions on 'recommended debugging techniques' but am also looking for more expert advice

3 Answers3

8

These mistakes are detectable by the system and simple to avoid: embrace immutability.

At least declare your documentList as final. This immediately causes the compiler to inform you about this particular error. Unfortunately, Java does not have all the good things from functional programming, like real immutable lists and higher-order functions (yet), but at least final means you cannot replace your initial list with a completely new one. You can still make mistakes like calling documentList.clear(), but those are much less likely to happen by chance.

Hence, as usual, I try not to even go down the road of having to detect such mistakes, but I try to write code in a style that immediately ensures such a mistake cannot happen at all. For good reasons, mutability is spelled as t-r-o-u-b-l-e, so never walk that road unless you have to. The more parts of your code that can be declared final, the better.

Frank
  • 14,437
2

The best way to catch such bugs is to prevent them from rearing their head during runtime. You can achieve that in several ways (which are not mutually exclusive):

  1. Write your code in a style that allows a compiler to pick up on the errors. Some examples are to make liberal use of immutability (const/final, as also described in the answer by @Frank), or to write equality test like this: 42 == x in a context where assignment would also be legal.

  2. Have a second pair of eyes look over your code (as in, perform a code review).

-3

In general you should write unit tests for preventing mistakes. With test driven development you build your components in small increments and constantly strengthen your test harness. As a result you have a more-or-less bug-free component which you don't need to debug afterwards.

Muton
  • 627
  • 4
  • 11