When to use which - multiple methods, multiple parameters, or an options parameter

天大地大妈咪最大 提交于 2019-12-05 07:27:04

The advantage of the options parameter is that it allows unlimited options without sacrificing clarity. When someone specifies data: or isSync: it's plainly obvious what settings are being filled in. Remembering to set the 13th parameter in a function to false is 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:

  1. 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.)

  2. 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 options object anyway, I'm just forcing you to make decisions in two different places. I'd rather have all the settings in one place.

How about having a "supermethod" with the json options for max flexibility, and then maybe some wrapper methods with more strictly defined parameters to have easy access to most commonly used functionality.

Obviously with multiple methods you'd need to have some sort of abstract supermethod they'd call, otherwise you'd repeat yourself, which is considered to be bad, however sometimes it is nice to have such methods as aliases or shorthands (see i.e. jQuery $.getJSON() for a modified $.ajax()-Call)

One Method with more parameters is not really flexible if you have a lot of spechial-case or optional parameters, for such you'd use a options object as you've mentioned in your 3rd example.

It really comes down to the use case and the needed flexibility/reusability. Personally I would always go with the One method, with an options parameter approach.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!