vendredi 24 juin 2016

Which way is better to encapsulate a single unit of work in Node.js, OOP or functional?

I have a complex buisness action for example deleting a user account. It contains multiple connected steps, and has to keep track of some state between steps. What is a better approach for writing this action?

I see a lot of more functional approach like one below.

function someAction(someParam, anotherParam, callback) {

    async.waterfall([
            step1,
            step2,
            step3,
            step4
            ],callback
    );

    function step1(p,cb){/**use someParam and anotherParam here via closure*/}
    function step2(p,cb){/**...*/}
    function step3(p,cb){/**...*/}
    function step4(p,cb){/**...*/}
};

someAction('value', 1241, (err)=>{/**...*/});

What I don't like about this approach is that everything is defined within the scope of a single function (here someAction).

I find a more object-oriented way to be a little more readable. The state and the stepX functions are not truly private - sometimes it is convenient for testing.

function SomeAction(someParam, anotherParam){
    //private state
    this._someParam = someParam;
    this._anotherParam = anotherParam;
};

SomeAction.prototype._step1 = function(p, cb){
    //use this._someParam and this._anotherParam
};

SomeAction.prototype._step2 = function(p, cb){
    //use this._someParam and this._anotherParam
};

SomeAction.prototype._step3 = function(p, cb){
    //use this._someParam and this._anotherParam
};

SomeAction.prototype._step4 = function(p, cb){
    //use this._someParam and this._anotherParam
};

//public api
SomeAction.prototype.execute = function(callback) {
    async.waterfall([
                this._step1,
                this._step2,
                this._step3,
                this._step4
            ],callback
    )
};

new SomeAction('value', 1241).execute((err)=>{/**...*/})

Is there any performance difference between them ? What is the recommended approach in Node.js ? Is it true that each time I callsomeAction in functional approach - all the stepX functions have to be defined from scratch ?

Aucun commentaire:

Enregistrer un commentaire