Functional Friday 3: Reverse the Reversing


!yadirF lanoitcnuF...s'tI

Today I'll use a slide from a presentation I gave to the Omaha Java User's Group Tuesday night, "Graph Theory in Software Design".

Imparative Code Graph Analysis

This piece if code decides if a word is typed with left hand only using standard touch typing technique, or if it a "boring" word (the full code checks right hand only, and alternating hands). Think about imperative code: code that runs step-by-step, changing memory as it goes. While FP principles came before the modern computer, most of our programming on computers has been imperative code, and I believe this is because this is exactly how CPU and RAM work. But if you take the process of the reading the code line by line, and put it in slow-mo, you realize that understanding the function and the purpose of each line of code is quite taxing. The slide shows a line between all lines/statements of code that depend upon each other for understanding, and therefore must also be stored in the reader's memory while gathering enough information to understand.

Now with a full understanding of that code, how would you explain what it does? Probably something like "If all of the words' characters are LEFT_HAND characters, return LEFT, otherwise return BORING." Now take the functional version of the code (Scala in this example):

if (word.forall(LeftChars.contains) Hand.Left
else Hand.Boring

Which one is more like plain English? And which pieces of the code create questions the reader must hold onto until the rest of the code is read? Not much; in fact not really any! Of course in C# we would use LINQ and have virtually the same benefits, but before LINQ, and in Java before the "Stream API", only an imperative approach was possible.

Conclusion? Imperative code is backwards!

In fact, the next time you're reading an imperative function, a good tip is to start at the return statement and read backwards from there; it's usually much more efficient, unless there are side effects you're having to track as well.