Testing for Reference Side Effects

I was testing some fairly complex code last week and ran across a classic bug related to pointer side effects. Here’s an ultra simplified example of the effect in C#. First suppose you have a class SomeData:

class SomeData
  public int n;
  public SomeData(int n) {
    this.n = n;
  public override string ToString() {
    return “n = ” + n;

Now suppose you have a second class Analyzer that needs knowledge of class SomeData and so one of the fields in Analyzer is a reference (pointer in lower level languages) to a SomeData object:

class Analyzer
  public double x;
  public SomeData sd;
  public Analyzer(double x, SomeData sd) {
    this.x = x;
    this.sd = sd;
  public double Compute() {
    return this.x + this.sd.n;

Now consider this call:

static void Main(string[] args)
  SomeData sd = new SomeData(7);
  Analyzer a = new Analyzer(5.0, sd);

Both the sd object and the sd field in the Analyzer object point to the same object. The Compute method has the side effect of changing the sd object. The output of the code above would be:

n = 7
n = 8

which may or may not be what you want to happen. In a simple example like this the side effect was easy to see but in very complex code such side effects can be difficult to detect.

This entry was posted in Software Test Automation. Bookmark the permalink.