Legacy code is a problem in all languages, even F#.
The super awesome Ilker Cetinkaya published an excellent article about “test implants”. I really recommend to read his post before you read this one. It’s a really well written story called “The quest of the test”.
I destilled his nice little story to this small F# code:
We have a function a that is part of a third-party API and a function b which is part of our own legacy code base. The problem is: we want to check that b has called a. without changing b’s signature. Ilker suggested to use a “test implant”. Let’s try to do something similar with our small F# code. Since we are in the land of functional programming our idea is to implant another function into b. So let’s rename b into b’ and add the implant to the parameter list of b’.
Of course we restore b’s behaviour by utilizing b’:
As you can see, we didn’t change the signature nor the behaviour of b. This is a typical refactoring in F#. The program runs as before. Now we want to write our test:
I hope you can see the similarity between this and Ilkers solution. The only difference is that we don’t use new constructors here. I really like this since it brings you one step further to nice functional design. What do you think?
Tags: F#, TDD, Test Driven Design, test implants