我有以下代码。我得到“避免在条件语句中使用文字”。在第5行的PMD中发出警告。
List<Object> listObj = getData();
if (listObj.isEmpty()) {
throw new NoEntity("No entity found for given Device.");
}
if (listObj.size() > 1) {
throw new MultiEntity(
"Multiple entity record found for given Device.");
}
我更喜欢不将全局静态final int变量赋值为1并在if条件中使用它。还有其他任何解决方案吗?
答案 0 :(得分:2)
最好的解决方案是使用//Controlling the back stack when the user selects the soft back button in the toolbar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (fragmentManager.getBackStackEntryCount() == 0) {
super.onBackPressed();
overridePendingTransition(R.anim.no_change, R.anim.slide_down);
} else {
if(!BaseFragment.handleBackPressed(getSupportFragmentManager())){
super.onBackPressed();
Fragment fragment = fragmentManager.getFragments()
.get(fragmentManager.getBackStackEntryCount());
fragment.onResume(); //Make sure the fragment that is currently at the top of the stack calls its onResume method
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
//Controlling the back stack when the user selects the "hardware" back button
@Override
public void onBackPressed() {
if (fragmentManager.getBackStackEntryCount() == 0) {
super.onBackPressed();
overridePendingTransition(R.anim.no_change, R.anim.slide_down);
} else {
if(!BaseFragment.handleBackPressed(getSupportFragmentManager())){
super.onBackPressed();
Fragment fragment = fragmentManager.getFragments()
.get(fragmentManager.getBackStackEntryCount());
fragment.onResume(); //Make sure the fragment that is currently at the top of the stack calls its onResume method
}
}
}
来抑制警告是如此简单的情况。
但是,对于您的示例,我有一个解决方案。
使用Guava的Iterables:
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
答案 1 :(得分:1)
如果您使用的是Apache Commons Lang,它可以在NumberUtils https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#INTEGER_ONE中找到
答案 2 :(得分:1)
您可以在前一行中添加分配以记录条件。它将提高可读性,同时使警告消失。
boolean multiEntityDevice = listObj.size() > 1;
if (multiEntityDevice) {
throw new MultiEntity(
"Multiple entity record found for given Device.");
}
答案 3 :(得分:0)
您可以将PMD配置中的rule definition修改为1作为MagicNumber。我看不出任何理由为何1不应成为规则本身的默认值之一。
<rule ref="category/java/errorprone.xml/AvoidLiteralsInIfCondition">
<properties>
<property name="ignoreMagicNumbers" value="-1,0,1" />
<property name="ignoreExpressions" value="true" />
</properties>
</rule>
如果您不想自己修改规则配置,可以对PMD on Github提出疑问。