コード例 #1
0
ファイル: CFG.java プロジェクト: SonarSource/ruling_java
 private void buildSwitchStatement(SwitchStatementTree tree) {
   // FIXME useless node created for default cases.
   SwitchStatementTree switchStatementTree = tree;
   Block switchSuccessor = currentBlock;
   // process condition
   currentBlock = createBlock();
   currentBlock.terminator = switchStatementTree;
   switches.addLast(currentBlock);
   build(switchStatementTree.expression());
   // process body
   currentBlock = createBlock(switchSuccessor);
   breakTargets.addLast(switchSuccessor);
   if (!switchStatementTree.cases().isEmpty()) {
     CaseGroupTree firstCase = switchStatementTree.cases().get(0);
     for (CaseGroupTree caseGroupTree : Lists.reverse(switchStatementTree.cases())) {
       build(caseGroupTree.body());
       switches.getLast().successors.add(currentBlock);
       if (!caseGroupTree.equals(firstCase)) {
         // No block predecessing the first case group.
         currentBlock = createBlock(currentBlock);
       }
     }
   }
   breakTargets.removeLast();
   // process condition
   currentBlock = switches.removeLast();
 }
コード例 #2
0
 private static CaseLabelTree getLastLabel(SwitchStatementTree switchStatementTree) {
   if (!switchStatementTree.cases().isEmpty()) {
     List<CaseLabelTree> labels =
         switchStatementTree.cases().get(switchStatementTree.cases().size() - 1).labels();
     if (!labels.isEmpty()) {
       return labels.get(labels.size() - 1);
     }
   }
   return null;
 }
コード例 #3
0
 @Override
 public void visitNode(Tree tree) {
   SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree;
   CaseLabelTree defaultLabel = getDefaultLabel(switchStatementTree);
   CaseLabelTree lastLabel = getLastLabel(switchStatementTree);
   if (defaultLabel == null) {
     reportIssue(switchStatementTree.switchKeyword(), "Add a default case to this switch.");
   } else if (!defaultLabel.equals(lastLabel)) {
     reportIssue(defaultLabel, "Move this default to the end of the switch.");
   }
 }
コード例 #4
0
 private static CaseLabelTree getDefaultLabel(SwitchStatementTree switchStatementTree) {
   for (CaseGroupTree caseGroupTree : switchStatementTree.cases()) {
     for (CaseLabelTree caseLabelTree : caseGroupTree.labels()) {
       if (JavaKeyword.DEFAULT.getValue().equals(caseLabelTree.caseOrDefaultKeyword().text())) {
         return caseLabelTree;
       }
     }
   }
   return null;
 }
コード例 #5
0
  @Override
  public void visitSwitchStatement(SwitchStatementTree tree) {
    int count = 0;
    for (CaseGroupTree caseGroup : tree.cases()) {
      count += caseGroup.labels().size();
    }
    if (count < 3) {
      context.addIssue(
          tree,
          ruleKey,
          "Replace this \"switch\" statement by \"if\" statements to increase readability.");
    }

    super.visitSwitchStatement(tree);
  }