Andreas Lundblad
Nov 1, 2015

Heisen String

Here’s a good (and somewhat surprising) reason keep your toString implementations free of side effects.

The program below will, as shown in the screen shot, output HeisenString[1] in a normal run:

Now suppose we want to debug this program. We set a break point right before the System.out.println and hit debug. Without really asking for it IntelliJ (and many other popular IDEs) show the string representation of the local variables:

This causes the toString method to be called one extra time during debugging, and as a result the program outputs HeisenString[2]: