Wednesday, March 5, 2014

Extracting reusable C++ templated functions from StringCalculator code

I've recently coded a solution to the StringCalculator kata in C++ using GoogleMock, (you can check its code in GitHub).

In one of the refactoring steps, I extracted the code that filters out not numeric tokens to a separated helper method: filterOutNotNumericTokens:

Once all the kata requirements were satisfied, I refactored this method a little bit more using C++11 copy_if algorithm:

We can use the same technique to refactor the method that ignores numbers greater than 1000, ignoreTooBig, from this:

to this:
 
Notice that we had to make notTooBig a free function in order to pass it to copy_if.

To keep it as a member function we'd need to write this less readable version:

which uses the bind1st and mem_fun functions from functional.

In this case, I think it's probably better to use a lambda:

In the two previous examples we eliminated duplication using the copy_if algorithm.

We can improve the readability of this code introducing a helper templated functions, filter:

Notice that filter works only for vector, copy_if is more general. But this leads to a bit more readable code for filterOutNotNumericTokens and ignoreTooBig:
 
We can also use filter to refactor the getNegatives method:
 
The same procedure can be applied to have a map templated function that uses the transform algorithm which can then be used to refactor the convertToInts method:

This map and filter functions that we'd refactored out from the StringCalculator code are pure functions that are highly reusable and will help us to avoid duplication in another projects.

No comments:

Post a Comment