Follow Single Argument Principle in TypeScript with Parameter Objects

1,592 reads

I’m a big fan of Bob Martin’s Clean Code, A Handbook of Agile Software Craftsmanship. I wrote about it (briefly) here: https://medium.com/@pagalvin/i-m-working-with-a-few-of-my-colleagues-on-an-official-set-of-programming-standards-47f79d46f183. He and co-authors lay out a set of principles among which are:

The best number of parameters to a function is zero.

Single-parameter functions are OK if you need parameters at all :).

Two or more probably indicate a need to refactor the function.

I’m not quoting the book here, just paraphrasing.

I try hard to keep my function parameters down to one or zero, but sometimes, it doesn’t feel right. Here’s an example:

The gist above shows a function that that uses jQuery to assign click handlers to icons. These icons are children to a parent element. I know the the ID of the parent and I know the jQuery selector required to find the appropriate icons.

The gist shows the same method implemented two ways. The first method takes three distinct parameters and would be invoked like:

In the second case, I’m passing an object:

It looks really similar to the three-parameter version and probably still constitutes a violation of the single-argument principle. That said, this approach feels pretty good for a couple of reasons:

When invoking the function, intellisense prompts me for the parameters.

I can fill in the parameters in any order I want. A small corollary to this — it’s harder for me to mistakenly swap parameters since intellisense is basically throwing labels in my face (see video below).

As I fill in the parameters, intellisense drops them from the suggestion list.

Lastly, when someone looks at the code, the programmer’s intent is immediately clear to them. In the second example, there’s no mistaking the difference between the string parameters. In the first example, you’re just passing strings. At a glance, it’s not easy to know what those are for. Intent is less clear.

In short, intellisense guides me through the process of filling in the parameters and helps reduces the risk that I make a mistake.

Here’s a video showing intellisense at work:

Is anyone else doing this? Tried it and stopped? Have any other objections? Please leave a comment and let me know.

</end>

Postscript: If you liked this article, you may also like my free book, Yet Another TypeScript Book. Please check it out.

Tags