Practicing What I Preach
Jeff Brekke astutely responded to my
ConfigurationTest:
I'm wondering why you chose to use the constructor instead of setUp()? I guess I've grown a habit to always use setUp() and I was just wondering what the reasoning was. I try to question my habits often. ;)
Good thing you questioned it, Jeff... because I was wrong! Oh, there's
nothing fundamentally wrong with using the constructor. The
initialization code need run only once to capture the original
system properties. But I put that code in the constructor for all the
wrong reasons. Indeed, I fell prey to a cunning programmer trap. You
see, I wanted to put the initialization code in the setUp()
method. It makes for nice symmetry with the tearDown()
method. When I'm reading tests and see those two methods, I know just
what's going on.
But just as I was going for the setUp() method, I was
struck by irrational fear: "Oh no, this initialization code could be slow.
I don't want it to run for every test method. That will be
really slow!" So, without measuring how slow, I took the bait. That's
right, I was prematurely optimizing. And it bit me.
For some reason I forgot that a new instance of the test case is created for each test method. Consequently, the test case constructor is run for every invocation of the setUp() method. That's just how JUnit works. I was assuming the constructor was only run once, and that putting the seemingly slow code in the constructor would save time. I was wrong. Not only did it not save time, but it also compromised the readability of my test.
Here's the really bad (read: embarrassing) part: I've been aggressively preaching the perils of premature optimization. Indeed, my name is on the chapter in Bitter EJB that warns of performance tuning antipatterns. And the very first antipattern in that chapter is, you guessed it... Premature Optimization!
Shame on me. Perhaps by publicly falling on my sword I'll remember next time to focus on code clarity first, then measure for performance, if it matters. Thanks for keeping me on the rails, Jeff.