Tuesday, April 22, 2014

Aspect Oriented JavaScript

Aspect oriented code is kind of a triviality in a functional programming language, but here are some simple patterns for aspect oriented programming. (Will be using Harmony arrow syntax.)

doLogging(loggingParams)(() => {
    doSecurity(securityParams) (() => {
        ...my code...
    })
})

function doLogging(loggingParams) {
    return (func) => {
        ...logging Stuff...
        func();
        ...more logging stuff...
    }
}

Here is another way of doing it.

function addSecurity(func) {
    return {
        ...security stuff...
        func()
        ...security stuff...
    }
}

/**************/

var myFunction = (params) => {
    ..my code...
}

myFunction = addSecurity(myFunction);

So presumably addSecurity would be in a closure where it had access to security stuff. The neat thing is that "func" would not have access to this security stuff. But here is a way to potential do it in Harmony with Proxies:

var securityCheck = (rightNeeded) => {
    return {
        apply: (target, thisArgs, args) => {
                ...check rights and maybe stop...
                target.apply(thiArgs, args);
            }
    }
}
var myFunction = Proxy((myParams)=> {
        ...my Code...
    },securityCheck(admin));

So Proxies don't exist yet and are yet another game changer for JavaScript frameworks along with getters and setters and Object.observe and so on..., but you don't need them them at all for an expressive aspect oriented programming.

No comments:

Post a Comment