#74 switch without default case

release_3.1
closed
nobody
None
5
2012-10-10
2002-06-04
Lars Kühne
No

It's usually a good idea to introduce a default case in
every switch statement.

Even if the developer is sure that all currently
possible cases are covered, this should be expressed in
the default branch, e.g. by using an assertion. This
way the code is protected aginst later changes, e.g.
introduction of new types in an enumeration type.

As an example consider the type

class AnimalTypes
{
int CAT = 0;
int DOG = 1;
}

In a switch statement over the animal type a default
should be introduced to make sure that later
introduction of BIRD = 2 won't go unnoticed.

This check should be configurable. If someone has a
better name than checkstyle.allow.missingSwitchDefault
please post it here.

Discussion

  • Simon Roberts
    Simon Roberts
    2003-04-14

    Logged In: YES
    user_id=116382

    <pre>
    public class SwitchDefaultCaseCheck extends Check
    {
    public int[] getDefaultTokens()
    {
    return new int[]{TokenTypes.LITERAL_SWITCH};
    }

    /**
     * For the given {@link TokenTypes#LITERAL_SWITCH}
    

    token, look at each of it's {@link
    TokenTypes#CASE_GROUP}
    * children.
    * @param aAST
    */
    public void visitToken( DetailAST aAST )
    {
    DetailAST detailAST = (DetailAST) aAST.getFirstChild();
    while (detailAST != null) {
    if (detailAST.getType() ==
    TokenTypes.CASE_GROUP) {
    if (detailAST.findFirstToken
    (TokenTypes.LITERAL_DEFAULT) != null) {
    // found a "default" token, check is complete,
    return
    return;
    }
    }
    detailAST = (DetailAST) detailAST.getNextSibling();
    }

        // No &quot;default&quot; token found
        log(aAST.getLineNo(), aAST.getColumnNo(), &quot;Switch
    

    statement has no default", new String[]{aAST.getText()});

    }
    

    }
    </pre>

     
  • Logged In: YES
    user_id=746148

    I've submitted a path ([ 714389 ] suggested implementation
    for rfe# 564199) about this rfe

     
  • Oliver Burn
    Oliver Burn
    2003-04-28

    Logged In: YES
    user_id=218824

    Added check MissingSwitchDefaultCheck