I don’t know how to get this across with the level of excitement it brought to me as I discovered it. But I’ll try.
I love TDD – the clarity, focus, and downright beauty it brings to software creation is absolutely one of my favorite parts of doing it. I love the learning that it drives, and I love the foundation it lays for a masterpiece of simplicity. It’s unparalleled as a programming technique — I only wish I would have caught on sooner.
I love Scala. I can’t seem to find the link – but there was a good list about how to shoot yourself in the foot in various languages – in Scala, you stare at your foot for two days and then shoot with a single line of code. The language is amazing in its ability to let you get across your meaning in a radically concise, but type-safe way. I often find myself expressing a thorough bit of business logic in one or two lines. Things that would have taken 20-30 lines in a typical C-derivative language. It’s a fantastic language.
Writing Scala – I’ve gotten into a situation that finally, powerfully, crystallized in an experience this morning. I spent probably an hour struggling to get at the most understandable, most flexible solution.
The situation is this – I have a class that’s definitely a reasonable size – 30-50 lines or so. In this case, most of the methods were one-liners. And they were one-liners that built on each other. The class had one Responsibility, one “axis of change”. I liked it as it was.
One problem that arose was that one of the methods was wrapping some “legacy code” (read: untestable – and worse unmockable). In my Java days – this wouldn’t have even arisen as a problem, because the method using the legacy code would have probably warranted its own class, and thus I could have easily just mocked that class. As it was, I considered it. But as I said, the class was very expressive, and said as much as it should have, without saying any more. To cut a one line method and make it a one line class…would have bordered on ridiculous – it would have been far too fine grained at any rate.
So what’s a code-monkey to do? Well – I tripped across this idea of a partial mock. Which, I would have derided as pointless in my Java days – and in fact, the prevailing wisdom on the interwebs – was that partial mocking is bad. I don’t want to do bad. By the way, if you haven’t googled it already – partial mocking is simply taking a class, mocking out some methods, but letting others do their original behavior (including calling the now mocked methods on the same class).
Anyway – the more I stared at the problem and balanced the two forces at play, the more I realized how right the solution really is. In my experience, in Scala, the scenario I just laid out is common, and the only real way to solve for it is with partial mocking.
(Big thanks to Mockito for providing this capability – so awesome!)