Menu

SwitchStmtsShouldHaveDefault

Developers
rdasilva
2007-08-23
2012-10-07
  • rdasilva

    rdasilva - 2007-08-23

    Although I agree that switch statements should always have a 'default', I've come across an issue for which I'd like the rule adjusted. Consider:

    public enum TestEnum { ONE, TWO };

    ... (assuming this switch statement and the 'getTestEnumValue()' are in different parts of the code, which is highly likely)

    switch (someObject.getTestEnumValue())
    {
    case ONE: // do something
    break;
    case TWO: // do something else
    break;
    default: throw new AssertionException(...);
    }

    This is fine because we know we'll get an exception if 'THREE' is added to the enum right? Well, only if you bother testing for it! If you change your code for 'getTestEnumValue()' to allow 'THREE' to be returned, but forget to change this switch (YOU WON'T GET A WARNING because it automatically covers all possible future alterations because you were told to add the default!), then you're toast! I'd rather have the rule adjusted or added so that in the case of an 'enum' you simply have to always cover all of the possible values that the 'enum' allows. This way you'll always get a warning and you should then remember to change any switch statements operating on the changed 'enum'. Otherwise you end up relying on your tests to be good enough, if you bothered writing them in the first place! Or worse still, you'll get the customer bothering you when they hit upon a situation where 'THREE' is returned! Frankly I wouldn't trust anyone I know to be able to write the proper tests for this.

    Also, I tried turning off the PMD rule for the method containing the switch statement by using '@SuppressWarnings("PMD.SwitchStmtsShouldHaveDefault")' applied to the method, only to get another warning (probably from Eclipse itself): "Unhandled warning token PMD.SwitchStmtsShouldHaveDefault". Anyone know how to sort this out in the short term (until hopefully a rule is written or adjusted)???

    Anyone clever enough to create this rule?

     
    • rdasilva

      rdasilva - 2007-08-23

      OK, done! ID: 1780343.

       
    • rdasilva

      rdasilva - 2007-08-23

      With: "YOU WON'T GET A WARNING because it automatically covers all possible future alterations because you were told to add the default!" I mean of course that the 'getTestEnumValue()' can return 'THREE', but may not do so in certain or most circumstances... and as such you might not spot the AssertionError until your customers get the code and find your bug.

       
    • Allan Caplan

      Allan Caplan - 2007-08-23

      This rule may make sense - and may be easier to do with the type resolution stuff, especially if the ENUM is in a different class

      Can you add a FR for it?

       

Log in to post a comment.