質問

I read Robert Martin's Clean Code: Function chapter. In this chapter, the best number of arguments of function is single argument. So, it is good to abstract that argument and function should be separated if it have various roles.

In practice, I wrote function that accepts single/plural arguments using Typescript like below.

Context

Our web server have various permissions to enable a specific functionality, thus client should separate each features per permission. To implement this, I wrote function which receives single/plural permission as argument and check that permission is permitted. At first, I wrote this code like below

const isPermitted = (permissions: Permission | Permission[]): boolean => {};

But, I have problem for naming argument name permissions because it could be single and plural. I considered between permission and permissions. Consequently, I concluded to change like below.

const isPermitted = (permissions: Permission[]): boolean => {};

Argument is single, but it always accepts array only. I thought it was good refactoring. In this context, is it proper solution?

役に立ちましたか?

解決

That smells a bit like Cargo Cult (One of the main things BTW 'Uncle Bob' is fighting against).

Yes, the best number of arguments for a function that only needs one argument definitely is one argument. Easy to read and easy to follow. But jumping through hoops to reduce the number of function arguments blindly will even complicate your code.

Imagine the following function that adds two numbers:

// 1
int add (int a, int b) {
   return (a + b);
}

Looks straight and easy. But: Oh. too many arguments, let's reduce that to one

// 2
typedef struct addition {
   int a;
   int b;
} Addition;

int add (Addition x) {
   return x.a + x.b;
}

Much better, a single argument (really? To me it looks rather convoluted)

What Uncle Bob promotes is rather avoiding the following:

typedef enum {
   ADD = 0,
   SUB,
   MUL,
   DIV
} Operation;


int calculate (int a, int b, Operation o) {
   switch (o) {
      case ADD:
         return a + b;
         break;
      ...
   }
}

The rule "do one thing and do it properly" comes before (and is definitely more important than) the "single argument" rule in Uncle Bob's books.

What you seem to be trying to do in your example is to ignore "do one thing" over "single argument" by writing a function that can either take one or more permissions and apply one or more.

You should rather write a function for one single permission and another function for a list of permissions (which may in turn repeatedly call the previous one). The caller will know very well what she needs in what specific case when you name your functions properly (e.g. setSinglePermission (permission) and setListOfPermissions (list))

ライセンス: CC-BY-SA帰属
所属していません softwareengineering.stackexchange
scroll top