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.