#402 MissingSwitchDefault needs option for ignoring enums

release_4.2
closed
nobody
Check (274)
5
2014-11-25
2006-01-03
No

The check MissingSwitchDefault should have an option
that allows it to ignore a missing default on a (fully)
enumerated enum.

Suppose an enum:

public enum MyEnum {
YES,
NO;
}

and a switch statement:

MyEnum myEnum = MyEnum.YES;
...
switch (myEnum) {
case YES:
System.out.println("Yes");
break;
case NO:
System.out.println("No");
}

There is no use in complaining about a missing default
statement, since this case will never occur.

Discussion

  • Oliver Burn

    Oliver Burn - 2006-01-03

    Logged In: YES
    user_id=218824

    Interesting idea - reminds me of my Ada days.

     
  • Dale King

    Dale King - 2006-01-04

    Logged In: YES
    user_id=130378

    It is still a good idea to a default to protect against
    additional values being added to the enum, so it would be a
    good idea to make the exclusion optional.

     
  • Michael Marquardt

    Meanwhile compilers (e.g. eclipse) can check if a switch statement contains all cases of an enumeration. A default statement is therefore not necessary for enumerations anymore.

     
  • Barney Barumba

    Barney Barumba - 2014-11-25

    Just came across this, and would like to add my +1 for this feature.

    It is still a good idea to a default to protect against additional values being added to the enum.

    Obviously subjective, but I disagree with this approach: I think it has the potential to mask problems later on. Consider the scenario:

    1. Write some code which has a switch which covers all enum values.
    2. Build / generate reports / review - no switch warnings generated.
    3. Later, add an new enum, value.
    4. Build / generate reports / review - ???.

    If you have added a default clause to your switch, then no warning will be generated in step 4, and the new enum value will activate the default clause. If the default clause throws an exception as often suggested then the code will fail at run-time, but I'd still prefer to have the warning at build time.

    If you don't add a default clause, then step 4 will now generate a warning.

    Just my $0.02, so adding the option and making it configurable should keep everyone happy...

     
  • Roman Ivanov

    Roman Ivanov - 2014-11-25

    Who will generate a warning on switch that does not cover all values?
    In my experience a switch that does not use all enum value is often scenaro.
    Checkstyle can not check that extression of switch is an Enum type, checkstyle is not aware of types at all. Checkstyle have no ability to analyse file other then current.

    If am wrong or you have more evidence please go mail list for discussion

     
  • Roman Ivanov

    Roman Ivanov - 2014-11-25
    • status: open --> closed
     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks