Lazy Evaluation

liskov_substition_principle

One of the recurring themes at QCon London was the demise of object-oriented programming paradigm, and the rise of functional programming. This was a big part of keynotes by Barbara Liskov, Damian Conway, and Greg Young. Since this topic was a major focus of QCon conference already last year, I've put much more attention to this issue in my day to day work over the last year. And once you start looking to the code (also) with the eyes of functional programming, you can quickly see cases where constructs of functional programming would make code much more elegant. One such functional construct that I increasingly miss in Python and Java is the concept of lazy evaluation, which delays the evaluation of an expression until its value is needed. For example, I often see the code that looks like this

[sourcecode language="python"] def process_data(self, data): stats = column_family_stats.get(data[KEY]) if not stats: return INVALID_CASE

pageviews = stats.get(PAGEVIEWS_KEY) if pageviews == 0: return NO_PAGEVIEWS

clicks = stats.get(CLICKS_KEY) ratio = float(clicks) / pageviews min_ratio = stats.get(MIN_RATIO_KEY)

if ratio < min_ratio: return RATIO_TOO_LOW

return VALID [/sourcecode]

Even in this small example, it's hard to immediately grasp what this function does. If we would have the concept of lazy evaluation at our disposal and we could separate manipulation of data from function logic, the code could be organized much better and it would like this

[sourcecode language="python"] def process_data(self, data): # Prepare data stats = column_family_stats.get(data[KEY]) pageviews = stats.get(PAGEVIEWS_KEY) clicks = stats.get(CLICKS_KEY) ratio = float(clicks) / pageviews min_ratio = stats.get(MIN_RATIO_KEY)

# Function logic if not stats: return INVALID_CASE if pageviews == 0: return NO_PAGEVIEWS if ratio < min_ratio: return RATIO_TOO_LOW

return VALID [/sourcecode]

I don't think we will see functional programming languages replacing existing procedural programming languages such as C++, Java, or Python. I think it's much more likely that these programming languages we'll see increasingly more functional constructs added to them, just like what happened 20-30 years ago with the object-oriented programming paradigm.

Enhanced by Zemanta