Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Let\'s say I have an object like this: function Foo() { this.parser = new DataPa

ID: 646695 • Letter: L

Question

Let's say I have an object like this:

function Foo() {
this.parser = new DataParser();
};
Within Foo I have a method that does something like this:

Foo.prototype.getResponse = function(message, callback) {
var payload = {data: message, type: 'normal'};
var response = this.parser.parse(payload, function(data){
    callback(data);
});
}
Now, let's say that somewhere else I need to call foo.getResponse(). Most of the time I want it to run just like this, but on occasion I need the format of the payload to be slightly different - let's say I need to specify a different type.

Would it be better to make a different method for this slightly different kind of request, like so...

Foo.prototype.getSimilarResponse = function(message, callback) {
var payload = {data: message, type: 'other'};
var response = this.parser.parse(payload, function(data){
    callback(data);
});
}
... or to take an option on getReponse, like so...

Foo.prototype.getSimilarResponse = function(message, type, callback) {
var payload = {data: message, type: type};
var response = this.parser.parse(payload, function(data){
    callback(data);
});
}
... or to do something else entirely?

Using a type option in the example above is a lot more DRY, but I don't like the way it requires the caller to know about payload type, which is really the concern of Foo and doesn't need to be exposed anywhere else.

How would you recommend approaching a situation like the above?

Explanation / Answer

I would recommend to pass the type argument 'optionally' so you'd get a function like:

Foo.prototype.getSimilarResponse = function(message, type, callback) {
if (typeof(type) === 'function') {
callback = type;
type = 'normal';
}

var payload = {data: message, type: type};
var response = this.parser.parse(payload, function(data){
callback(data);
});
}
That way, your code is DRY and you don't have to worry about the type if you don't want/need to.