英文:
Sonar issue - Switch cases should end with an unconditional "break" statement
问题
Sonar在下面的代码中将案例EQUALS标记为sonar问题squid:S128。
- Switch语句应以无条件的“break”语句结束。
我不认为在这种情况下我需要添加“break”语句。
有人可以帮助我吗?这是误报吗?
提前致谢。
英文:
I would like to ask you for your help with sonar issue. Sonar marked case EQUALS in the code below as sonar issue squid:S128.
-Switch cases should end with an unconditional "break" statement.
I dont think that in this case I have to add "break" statement.
Can someone help me? Is it false positive issue?
Thank you in advance.
public boolean causeException(Throwable throwable) {
Throwable causeException = ExceptionUtils.getRootCause(throwable);
Map<String, MatchMode> configuration = infoMessage.get(causeException.getClass());
String message = throwable.getMessage();
for (String key : configuration.keySet()) {
MatchMode matchMode = configuration.get(key);
switch (matchMode) {
case EQUALS:
if (message.equals(key)) {
return true;
}
case CONTAINS:
if (message.contains(key)) {
return false;
}
}
}
return false;
}
答案1
得分: 2
你的消息与关键字不相等时,会出现 fallthrough。你需要添加 break 来解决这个问题:
public boolean causeException(Throwable throwable) {
Throwable causeException = ExceptionUtils.getRootCause(throwable);
Map<String, MatchMode> configuration = infoMessage.get(causeException.getClass());
String message = throwable.getMessage();
for (String key : configuration.keySet()) {
MatchMode matchMode = configuration.get(key);
switch (matchMode) {
case EQUALS:
if (message.equals(key)) {
return true;
}
break; // 停止 fallthrough
// 如果没有 "break",它还会执行 CONTAINS 块
case CONTAINS:
if (message.contains(key)) {
return true;
}
break; // 停止 fallthrough
default:
// 仅为了清晰起见
break;
}
}
return false;
}
英文:
You're going to get fallthrough if you message doesn't equal key. You need to add breaks to address this issue:
public boolean causeException(Throwable throwable) {
Throwable causeException = ExceptionUtils.getRootCause(throwable);
Map<String, MatchMode> configuration = infoMessage.get(causeException.getClass());
String message = throwable.getMessage();
for (String key : configuration.keySet()) {
MatchMode matchMode = configuration.get(key);
switch (matchMode) {
case EQUALS:
if (message.equals(key)) {
return true;
}
break; // stops fallthrough
// With no "break" it would do the CONTAINS block as well
case CONTAINS:
if (message.contains(key)) {
return true;
}
break; // stops fallthrough
default:
// just for clarity
break;
}
}
return false;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论