This question is coming from a javascript point of view, but it certainly could apply to other languages.
I have been running into this more and more lately, and was wondering if there was a best practice, or at least good design standard, for when how to build your methods.
The obvious options that I see are as follows, along with a trivial example for each
-
Multiple methods:
this.makeGetRequest = function(controller){...} this.makeSynchronousGetRequest = function(controller){...} this.makePostRequest = function(controller, data){...} -
One method, with more parameters:
//data would be an optional parameter // this.makeRequest("friends", "GET", true); // this.makeRequest("friends", "POST", false, newFriend); this.makeRequest = function(controller, type, isSynchronous, data){...} -
One method, with an options parameter:
this.makeRequest = function(controller, type, options); this.makeRequest("friends", "POST", {data:newFriend, isSync:false});
The HTTP requests example is just motivated the question, but this works for any public facing function with varying amounts of customization/variables.
All three are obviously just as functional. But what’s good practice? Is there a standard, or guideline that tends to be followed?
The advantage of the
optionsparameter is that it allows unlimited options without sacrificing clarity. When someone specifiesdata:orisSync:it’s plainly obvious what settings are being filled in. Remembering to set the 13th parameter in a function tofalseis a recipe for confusion.So, between the last two options I only use multiple parameters in cases where (1) there are fewer than four parameters in total, (2) the sequence is logical and easy to remember (URL, then type, then data), and (3) no more than one (the last one) is optional. That’s as a rule of thumb, anyway.
How about multiple methods versus parameterization? Multiple methods is only an option to begin with when you have a small number of possibilities (GET vs. POST, UseDefaults vs. DontUseDefaults, or whatever). Thinking about it, I’m likely to setup separate methods only when:
The distinction is highly important (a synchronous request behaves fundamentally different from an asynchronous request and I want the developer consciously choosing which to apply. (Whereas by contrast GET vs. POST is just one more property of your request — it’s not an end-all, deal-breaking decision if you do it wrong.)
There aren’t other options you’ll want to set anyway. If I first have to remember whether to call foo.get() or foo.post() and then remember to fill in an
optionsobject anyway, I’m just forcing you to make decisions in two different places. I’d rather have all the settings in one place.