2010-06-10

Interesting Powers of Local Variables

I interviewed a Java developer recently and he had a very interesting (incorrect) interpretation of how local variables work in regards to method calls.

This candidate understands that when you pass an object to a method, the method may modify the data in that object, so that when you look at that object after the method call, it will have changed.   This is correct behavior.   For example:

public void addData(List<String> values) {
  values.add("data");
}

...

List<String> myValues = new ArrayList<String>();
addData(myValues);
assertTrue( myValues.size() == 1 );


Here's the interesting part.  The candidate believes that if you were to return a mutable object from a method and assign it to a local variable, the changes stay with that local variable.  For example:

public class Foo {
  private List<String> values = new ArrayList<String>();

  public List<String> getValues() {
    return values;
  }
}

...

Foo foo = new Foo();
List<String> myValues = foo.getValues();
assertTrue( myValues.isEmpty() );
myValues.add("data");  // mutate "local" variable

assertTrue( foo.getValues().isEmpty() );  // WRONG

The candidate insisted that there was only a single instance of the List, which made the conversation very confusing.  This caused a long discussion.  In the end, I believe that his thoughts are that local variables have the ability to hold object "deltas" in a way that aren't reflected back to the original object.

Although interviewing candidates is very time consuming, there are moments like this that I find fascinating.  It's very interesting to hear other peoples interpretations on how the language works.

No comments: