It was really trivial code. A wrapper around a HashMap (dictionary) to temporarily cache some values that were getting too expensive to calculate every time. While writing it, I pretty much convinced myself that this code was so simple there was really no point writing unit tests, but as I got close to checking the code in I realised that the first thing my code-reviewer would ask was “where’s the test?”
So I wrote a test. And it failed. It failed because I'd made a really dumb typo in the constructor of one of the nested classes I was using as cache keys, writing this.username = (user == null) ? null : username instead of this.username = (user == null) ? null : user.getName(). This simple mistake meant my cache would be at best useless, and far more often entirely inaccurate.
Lessons for the day, there are two:
- Nothing is too trivial to test
- Even the mere threat of a code-review leads to better code
If username had been final you wouldn't have been able to make that mistake, if I'm interpolating correctly.
True. Which exposes another mistake: I could have sworn I'd made it final when I wrote it!
If it's not tested, it doesn't work.
Or at best, you don't know, and a customer will one day do the finding out for you...
It's so true, specially when you think that unit tests make the deveolpment process a lot faster since you don't have to deploy applications or restart application servers when testing stuff through JUnit.
I beg to differ. There are a lot of things that are too trivial to test, your code just doesn't qualify as trivial.
I think that the lesson here is not to subclass classes that should be used directly with the help of generics
I think the lesson here is that you can't tell much about a piece of code from a single line of pasted context, but that's not going to stop anyone from making entirely irrelevant comments on the Internets.
you're right! :) clear code gives you clear mind
But I prefer to avoid ternary constructions at all and I've changed highlighting them as error by default). if-else is more clear to read! yes, if-else must have braces too :)
These rules I use with different languages, editors and envirounments.