琐碎的问题,但对我来说很重要,我也想像其他问题。有人有一个非常好的,非常聪明的解决方案吗?
void some_function (obj &A, obj &B)
{
// do stuff with A...
//e.g.
double number_A = (value - A.member_func() ) * A.other_func();
// do stuff with B. similar BUT NOT EXACTLY like A...
//e.g.
double number_B = (value + B.member_func() ) * A.other_func();
// !!!!
// Big time TYPO - should say "B.other_func()", not "A.other_func()" !!!!
// !!!!
}
有什么好的方法可以防止此类错误?
我经常不得不处理两个类似的变量,比如说一个命名版本为“A”,另一个命名为“B”。
因为每个代码都相似,所以我经常将在“A”上使用的代码用作“B”上使用的代码的"template"(即复制和粘贴)-进行一些小的调整,使代码变得适用于B。
因为我是人,所以有时我在复制代码时忘记将某些位置的“A”更改为“B”。如果幸运的话,这将导致程序崩溃。无论哪种方式,这都是灾难性的。
有人知道防止这种错别字的聪明技巧吗?
我想到了
{ }
中以尝试限制变量的范围-但是,如果对象A和B在函数参数中,则此方法无法解决。 { scope-control }
了。同样麻烦,(即使我非常非常频繁地调用该函数,定义指针的开销也是可以忽略的,对吧?)最佳答案
在您给出的示例中,最好的防御方法是在每个函数中做的尽可能少:
void some_function (obj &A, obj &B)
{
double number_A = do_stuff(A);
double number_B = do_similar_stuff(B);
}
double do_stuff(obj &A) {
return (value - A.member_func() ) * A.other_func();
}
// EITHER
double do_similar_stuff(obj &A) {
// no variable rename when copying == no problem
return value + A.member_func() ) * A.other_func();
}
// OR
double do_similar_stuff(obj &B) {
// A not in scope == very brief problem until compiler tells us
return value + B.member_func() ) * A.other_func();
// Beware, also, the nightmare scenario that there's some *other*
// `A` in scope, so this *still* compiles. For that reason, prefer
// the other option unless there's some good reason why this parameter
// should be `B`, and don't name member function parameters the same
// as data members etc.
}
或者,您可以使两种“ Material ”之间的关系明确。假定
B
代码中不匹配的括号应该与A
放在同一位置。这完全取决于两个看起来相似的操作之间是否确实存在逻辑关系:void some_function (obj &A, obj &B)
{
double number_A = do_stuff(A, true);
double number_B = do_stuff(B, false);
}
double do_stuff(obj &A, bool subtract) {
// yeah, never call variables "tmp". Unless you have no context
// to give them meaning.
// Depending on the type of `tmp`, there might be a better way to
// write this, using multiplication by -1. But let's not assume, we'll do
// one refactor at a time.
auto tmp = subtract ? value - A.member_func() : value + A.member_func();
return tmp * A.other_func();
}
其他示例将有所不同。正如您所说,编写起来可能很麻烦,但是除了捕获此错误之外,它还有许多其他好处。尤其重要的是,它将引导您以避免传递/返回许多变量的方式编写代码。因此,代码的每一行都会影响程序中更少的其他内容,这是基本的代码卫生。
这也可能意味着您可以独立于
A
的公式是否正确来测试B
的公式是否正确,以及其他简短函数的好处。关于c++ - 良好做法-命名类似的变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12463667/