为 C++ 调制代码

Modulating Code for c++

我听说最好 'modulate' 您的代码,以尽量减少您的代码对代码其他部分的依赖。

如果我有 float:

float X = 1000;

和一个使用X的函数:

void A()
{
    //use X
}

对于函数来说,直接使用 X 还是像这样使用传递的参数更好:

void A(float param)
{
    //use param
}

并这样称呼它:

A(X);

还是简化使用第一个函数?

决定某物是参数还是全局的最佳经验法则就是 "will you ever call it with a different argument"?也就是说,A 是否需要 X 的不同值?

如果X是一个常量,比如字节中的位数或引力常数,就让它成为常量,不要浪费时间将它作为参数传入。另一方面,如果它可能因调用而异,那么请将其作为参数。

此外,不要进行不必要的模块化。如果你只在一个地方使用 A,并且 A 不是特别长,那么你最好将它放在行内 - 它会减少某人必须阅读的代码量理解您的代码。

如果您仅为函数 A() 全局声明 X,那么您不应该这样做。 而是在 main 中本地声明它并通过参数将其传递到函数中。

此外,如果您只是为了函数声明 X 并想修改它的值,您应该通过引用传递它。

void main ()
{
    float X = 1000;
    A(&X)
}

void A(float *ptr)
{
    // Do operations with *ptr which has the value of X in main()
}

这个例子不好:

// Define global variable ...
float X = 1000;
// ... and expect A() to work with it ...
A();
// ... because there is a hidden dependency.

这个例子很好:

// Define local variable ...
float X = 1000;
// ... and let A() work with it.
A(X);
// Everything is explicit and clean here.

请注意,好的方法 允许您以这种方式简化代码:

// Just do it.
A(1000);