I.24: Avoid adjacent unrelated parameters of the same type(避免相同类型的无关参数相邻)

 

Reason(原因)

Adjacent arguments of the same type are easily swapped by mistake.

相同类型的毗邻参数很容易被弄反。

Example, bad(反面示例)

Consider(考虑下面的代码):


 


 

void copy_n(T* p, T* q, int n);  // copy from [p:p + n) to [q:q + n)

This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.

这个K&R C风格接口的危险变种。它很容易弄反to和from两参数。

译者注:译者注:K&R指《The C Programming Language》一书的作者Kernighan和Ritchie二人,K&R风格指他们在该书中书写代码所使用的风格。

Use ​​const​​ for the "from" argument:

为from参数使用const修饰。

 

void copy_n(const T* p, T* q, int n);  // copy from [p:p + n) to [q:q + n)

译者注:如果from缓冲区为const类型,弄反参数就会产生编译错误。

 

Exception(例外)

If the order of the parameters is not important, there is no problem:

如果参数的顺序不重要,则没有问题:


 


 

int max(int a, int b);


 


Alternative(可选做法)

Don't pass arrays as pointers, pass an object representing a range (e.g., a ​​span​​):

不要以指针形式传递数组,传递一个·表现range的对象(例如span):


 


 

void copy_n(span<const T> p, span<T> q);  // copy from p to q


 


Alternative(可选做法)

Define a ​​struct​​ as the parameter type and name the fields for those parameters accordingly:

将参数类型定义一个结构体并为并根据参数为字段命名:

 

struct SystemParams {    string config_file;    string output_path;    seconds timeout;};void initialize(SystemParams p);

This tends to make invocations of this clear to future readers, as the parameters are often filled in by name at the call site.

由于参数通常被调用者根据名称赋值,这样做有助于将来的读者更明确地调用该函数。

Enforcement(实施建议)

(Simple) Warn if two consecutive parameters share the same type.

(简单)如果有两个连续的参数的类型相同,报警。