Maybe Thinking

A coworker of mine recently submitted a pull request introducing some simple
reporting into an application, where he was displaying an average time to
complete a survey or "not enough results" otherwise.

In this case, team_result_completion_times (not shown) can return an array
of zero or more integers representing the number of seconds it took to complete a
survey. When we have results, we display the length of time (e.g. "20
minutes" or "3 days").

What struck me as interesting was that checking emptiness of
team_result_completion_times was effectively a guard clause against
dividing by zero. This results in interacting with
team_result_completion_times in two different methods, and any other places
that use team_result_completion_times need to also check for the length of
the array (or risk odd behavior).

Here, we have two functions (named similarly so it’s easier to draw parallels
between the two implementations).

The difference here is that averageTeamCompletionTime returns a Maybe
Float (take a look at the docs on Elm’s implementation of Maybe if
you’re unfamiliar), and we encapsulate both when the list is empty and when
the list has values in only one spot. Instead of having both functions operate
on the length of the list to determine which string to display,
completionTimeAverageInWords relies on averageTeamCompletionTime to do all
the work, just like we want.

Introducing Maybe in Ruby might be overkill (or it might not be?), but it
did hone in on the problem of spreading length logic across potentially
multiple methods. Instead, it might be safest to check for nil (since, if
it’s forgotten, it’ll be easier to spot when something breaks):

I considered using a case statement in Ruby checking when the value was
Float::NAN and handling the “nothing” case there; however, I realized that
forgetting to check for both paths and performing an operation “infinity”
times or transferring “infinity” dollars would be problematic.

While perhaps not as elegant as Elm’s handling of Maybe, this seems like a
better direction to go in than introspecting on an external source of
information in two methods. This then places the responsibility of caller of
average to handle both when the average present and when it is nil.