wtorek, 12 marca 2013

Pure functions in Object Oriented World

Let's suppose we have a class called Time with method convertToGMT(...). The method has one parameter called time, it converts the parameter to the GMT and returns the result.

For some reason (and please let's don't try to question this reason for the sake of this short exercise) the actual time zone of the caller is an instance variable of the Time object. It may be set when the object is constructed or re-set afterwards.

convertToGMT simply checks the time zone by accessing the instance variable timezone, performs calculation and based on that returns the GMT result.

When writing a couple of unit tests to test how convertToGMT works for different time zones, we would have to repeatedly:
  • set the time zone by calling the presumed Time.setTimeZone(...) method
  • call convertToGMT and check the result
We would do that for each time zone - time-to-be-converted pair we want to test. Clearly, this function is not a pure function, since its result depends on the state of the object. Programmers with no functional background would probably not notice the impurity. However, we could legitemately ask the question: can we make our tests look cleaner in this case?

We could add a helper function _convertToGMT (with underscore) that would take two parameters instead of one: actual time and timezone. The function would be a pure function. We could write all our test cases without meddling at all with the state of the Time object, just checking the result of calling _convertToGMT(time, timezone) each time for different pair of parameters. Then, after covering all desired test cases, we would add just one or a couple to test that convertToGMT correctly makes use of _convertToGMT by passing the instance variable timezone as the second parameter.

Of course, this is a very simple example with just one parameter and one instance variable, but in your real code you can have more interesting cases where this technique could be useful.

How is it called? I have no idea. If you have seen this already elsewhere, please let me know.

Brak komentarzy:

Prześlij komentarz