lundi 23 juillet 2018

Best design pattern for wrapper

So... I've been coding up a wrapper (I'm calling it Medium) that seems to be working just fine. Problem is it's pretty ugly.

At first I was making it as a simple constructor with some private attributes and getters and the prototype:

var Medium = function(fn, args){
    var __fn = cloneFunction(fn);
    var __length = fn.length;
    var __args = args.length >= fn.length ? args : fill(fn.length, args);
    var __self = this;

    this.getFn = function(){ return cloneFunction(__fn) };
    ...
}

Medium.prototype.pass = function(sprdArgs){
    var fnArgs = this.getArgs();
    return arguments.length > 0 
         ? this.use("load", arguments) 
         : this.use("update", fnArgs);
}
...

Then I thought it would be cool to add some methods visible to the Medium itself but not to the user. I haven't found a good solution, so I just moved this methods to a getter that returns the called function only if the this values matches:

var Medium = function(fn, args){
    ...
    this.method = function(thisArg, funcName, args){
        var funcs = {
            load: function(args){ ... },
            update: function(params){ ... },
            execute: function(){ ... }
        };

        return thisArg === __self
            ? funcs[funcName].apply(thisArg, args)
            : null;
    }
}

Medium.prototype.use = function(funcName, sprdArgs){
    var args = clone(arguments);
    var sprdArgs = filter(args, function(elem, i){
        return i !== 0;
    });

    return this.method(this, funcName, sprdArgs);
}

Thing is, I also have a pipe function and it uses apply. Result: I pass the functions to my pipe, and the this value goes null. Nothing big 99% of the time, but with Medium it simply breaks all the getter's stuff.

In order to repare Medium uses prototype no more. All the functions are declared inside the constructor. Unfortunally, this makes it hard to read - and I thing it may cause other problems since in the research I have done about wrappers people usually recomended to implement behaviour on the prototype.

Just in case, I have made a JSFiddle of the whole thing. You can see it here: https://jsfiddle.net/hguerra/0q1urc9o/15/

OBS: You can see some strange functions like filter, reduce and stuff. Yeah, they are the Array's ones. The build of JS I'm using fails to have any array-related functions so I have made my better to pollyfeel everyone of them. For what I can say, they all work as you should expect for expection of push and unshift; these two returns the new array instead of the new length. Anyway, these functions are also on fiddle so you can check there if you have any doubts.

Aucun commentaire:

Enregistrer un commentaire