Friday, July 22, 2011

Functional Patterns in our Everyday Code

Modern Programming
During the advent of modern programming, which I think of as post 2005 code base, we have received many enhancements to our programming toolsets.  Much ado has been made about these enhancements, often these are the frameworks that Web 2.0 has been built on.
The modern programming tools are very aware of the upcoming Mobile Application Flood,  but they also own a considerable amount to older programming techniques first developed in LISP as early back as the 1960's.  Python popularized much of the functional programming style, and was incorporated into ECMAScript. 

Functional Programming
Javascript and its adopted parent ECMAScript were developed with functional capabilities from the very beginning. Methods in JavaScript are first class and can be passed as around as arguments. Consider the following Native Javascript Code:


<script language="ecmascript" type="text/ecmascript">
    Array.prototype.AlertOnce = function () { alert('A') };
    [1, 2, 3].AlertOnce();
script>


The script applies an anonymous function to the array object as an extension method, via the prototype pattern.

In the script below, the anonymous function iterates the array, and runs once per primary object occurrence in the array.


<script language="ecmascript" type="text/ecmascript">
    var IEnum = [1, 2, 3];
    IEnum.forEach(function (ele, i) {
        alert(i + ':' + ele)
    });
script>


Contrasted with the JQuery Method, below. The methods are almost identical.


<script language="ecmascript" type="text/ecmascript">
    var IEnum = [1, 2, 3];
    $(IEnum).each(function (i, ele) {
        alert(i + ':' + ele)
    });
script>


As compared to a Lambda expression in VB.Net


Dim IEnum = New List(Of Integer)(New Integer() {1, 2, 3})
IEnum.ForEach(Function(i) System.Diagnostics.Debug.Print( i ) )

or in C#

List<int> IEnum = new List<int>(new int[] { 1, 2, 3 });
IEnum.ForEach(i => i.ToString());


These scripts demonstrate multiple ideas. To wit, JavaScript natively supports the sort of iterating across collections pattern that we usually think of JQuery for. And .net now supports a wide set of functional programming, this now includes anonymous methods, JavaScript like prototyping via extension methods (and on those extension methods, even method chaining).

Conclusion:
Instead of thinking about JQuery, or .Net extension methods, we should be seeing these new pieces as functional programming patterns and getting used to thinking in terms of delegates, callbacks and prototypes.

No comments: