简体   繁体   English

避免在Qt中使用非符号常量

[英]Avoiding non symbolic constants in Qt

One thing that often comes up in code reviews I participate in is 'magic numbers' inline in code as being a bad thing. 我参与的代码审查中经常出现的一件事是在代码中内联的“魔术数字”是一件坏事。

The preference is that a symbol be assigned somewhere. 首选是将符号分配到某处。

Now what I am working with at the moment is in the QT sdk. 现在,我目前正在使用的QT SDK中。 The class member QButtonGroup.checkedId() will return -1 as a magic number to signify that there are no radio buttons in the group selected. 类成员QButtonGroup.checkedId()将返回-1作为魔术数字,以表示所选的组中没有单选按钮。

And if I write something like 如果我写这样的话

if ( buttongroup->checkedId() == -1 )
{
   //yadda yadda
}

it will come up in the code review. 它会出现在代码审查中。

While certainly I can define a const static int symbol to give me that -1 , I'd much rather use something in the Qt namespace if it has a relevant constant defined. 虽然可以定义一个const static int符号来给我-1 ,但是我更愿意在Qt名称空间中使用一些已定义相关常量的东西。

Is there such a symbol already defined?? 是否已经定义了这样的符号?

Code reviews are about your code not the code of 3rd party libraries so you can't and shouldn't deal with it. 代码审查与您的代码有关,而不是与第三方库的代码有关,因此您不能也不应处理它。 Qt doesn't have any named entity to compare against so you have to compare the resulting code against -1 . Qt没有任何可比较的命名实体,因此您必须将结果代码与-1比较。 There is a bright side about it, though: -1 is a broadly understood magic number so there should not be any misunderstanding — it is used in many different languages and libraries. 但是,它有一个好的方面: -1是一个广为人知的幻数,因此不会有任何误解-它在许多不同的语言和库中使用。 However bad it is it is here and we have to live with it. 无论它多么糟糕,它都在这里,我们必须忍受它。

No such symbol is predefined; 没有预定义这样的符号; you would have to define it yourself. 您必须自己定义它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM