Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
1  
Every class, module or whatever has a documentation, and when a user needs to use it, he just reads that documentation. Here I see the same, I agree with the answer below, It's better to have a customizable method that a lot of functions with small changes. – e.campver Mar 17 at 4:37
@e.campver Thanks for the insight, I appreciate it. – Andrew Mar 18 at 16:03

1 Answer

up vote 4 down vote accepted

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.

share|improve this answer
This is what I'd probably do, also, The question doesn't have much to do with OOP. This is also pretty much how every node.js api works. – Benjamin Gruenbaum Mar 16 at 21:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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