1

I'm writing javascript object that wraps REST requests. For every operation on the server there is a method that accepts the parameters for the request and a callback that will receive the results. (The method issues a jQuery $.ajax()-call and prepares the settings for $.ajax().)

Each method has the same structure: call a custom method (this.post()), setting some parameters to constant values (e.g. the operation name) and passing some other parameters (i.e. the request parameters and the callback). For example:

service.GetMessages = function(startIndex, onDone) {
    return this.post('GetMessages', startIndex, onDone);
}

Because many of these functions are similar we can use Function.bind() to generate a 'bound function' instead of manually defining all these functions. For example (with RestService being the class I'm writing):

service.GetMessages = RestService.prototype.post.bind('GetMessages');

The downside of this approach is that the parameters accepted by GetMessages are now undocumented; i.e. when manually writing functions that bind parameters, as in the first approach, the declaration shows that the functions accepts startIndex and onDone as parameters, with bind this information is lost.

How can I combine avoiding repeating code, as done via bind while preserving the documentation that the function declaration provides?

1

(This should have been a comment, but I don't have enough reputation to make one)

How about the "old" way of documenting code - comments? Each time you use the bind()-function, you can explain what is happening in the line above the code(or below, but it's usually above) with a comment, just as detailed as you need it.

  • Good idea, a downside of comments is that my colleagues using the RestService object have to go to the definition of the bound function. With normal functions that declare their parameters the IDE (in our case Visual Studio) provides a tooltip that details what the function expects when someone tries to call the function. With comments this is lost; i'll try intellisense xml api doc comments. Perhaps the "old" way is the best we have. – Kasper van den Berg Nov 4 '16 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.