Saturday, July 11, 2009

how can you be so sure?


I'll preface this story by saying that I don't think I'm unusual in my confidence level. I am comfortable and generally feel confident with what I know, and am not so confident when straying into areas where I have less experience.

That being said, when the code suddenly stops working the way I think it should, my confidence level drops like a stone. Sometimes, I'll immediately assume that there's some hidden rule, unknown to me, causing the strange behavior.

Yesterday, as I was stepping through the code with a debugger, I saw something happen which just isn't supposed to happen. I had an object of type Apple, which extends class Fruit. (Needless to say, class names have been changed to protect the innocent). Both classes had a getSize() method. When that method was called, the getSize() method of the Fruit class was being exercised, not the corresponding method of the Apple class. It went something like this:

  Fruit fruit = doSomethingComplicated();
  int sz = fruit.getSize();
  ..
}
protected Fruit doSomethingComplicated() {
  ...
}

Way down the call stack, doSomethingComplicated() was creating an instance of Apple, so fruit.getSize() should use the getSize() method of Apple, not Fruit. Yet I could see that the Fruit getSize() method was being called.

Just as I noticed this problem, and was thinking "whoa, what's that about??", a coworker came over and I explained what I was seeing to her. She seemed pretty sure that it was simply not happening, even though I could show her by stepping into the debugger that indeed, it was happening. Basically, I believed what my eyes were telling me, and she didn't.

She was right, and I was wrong. I had failed to notice that midway down the call stack, a new instance of Fruit class was being returned, not the original instance of Apple that I had seen created at the bottom of the call stack. I don't feel too bad about not noticing this, since it had escaped the eyes of my coworker too, even after we had stepped through with the debugger a couple of times.

What makes me feel bad is that I had such uncertainty about the way inheritance works in Java that I wasn't sure the behavior I saw was completely insane; in contrast, my colleague seemed convinced that something was totally wrong.

I really need to put some study time into relearning some of the basics, in addition to training on new material, to achieve that level of confidence!

No comments:

Post a Comment