Search code examples
javaparsingif-statementjavaparser

Calculate total number of if-else clauses(including nested)


Need to calculate the number of if-else clauses. I'm using java parser to do it.

What I've done till now: I've obtained the count of all if and else-if clauses by using the function

node.getChildNodesByType(IfStmt.class))

Problem: How do I count the else clauses? This function ignores the "else" clause.

Example:

if(condition)
{ 
     if(condition 2)
       //
     else
 }

 else if(condition 3)
{
     if (condition 4) 
      // 
     else
}
 else
{
   if(condition 5) 
      // 
}

In this case, I'd want the answer to be 8 but the size of the call will return 5 because it encounters only 5 "if's" and ignores the else clauses. Is there any function that can directly help me count the else clauses?

My code:

  public void visit(IfStmt n, Void arg) 
            {
            System.out.println("Found an if statement @ " + n.getBegin());
            }

            void process(Node node)
            {
                count=0;
                for (Node child : node.getChildNodesByType(IfStmt.class))
                {
                    count++;
                   visit((IfStmt)child,null);   
                }
            }

Solution

  • This answer has been solved on the following github thread. The in-built methods of the java parser are more than sufficient to help out.

    Answer:

     static int process(Node node) {
        int complexity = 0;
        for (IfStmt ifStmt : node.getChildNodesByType(IfStmt.class)) {
            // We found an "if" - cool, add one.
            complexity++;
            printLine(ifStmt);
            if (ifStmt.getElseStmt().isPresent()) {
                // This "if" has an "else"
                Statement elseStmt = ifStmt.getElseStmt().get();
                if (elseStmt instanceof IfStmt) {
                    // it's an "else-if". We already count that by counting the "if" above.
                } else {
                    // it's an "else-something". Add it.
                    complexity++;
                    printLine(elseStmt);
                }
            }
        }
        return complexity;
    }