Default label should be last in a switch

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: java-best-practices/default-label-not-last-in-switch

Language: Java

Severity: Notice

Category: Best Practices

Description

The widely adopted convention is putting the default statement at the end of a switch statement. By adhering to this practice, your code becomes more comprehensible and predictable for developers who engage with it in the future.

Non-Compliant Code Examples

public class Foo {
   void bar(int a) {
      switch (a) {
         case 1:
            break;
         default:  // this should be the last statement
            break;
         case 2:
            break;
         case 3:
            break;
      }
   }
}

Compliant Code Examples

public class Foo {
   void bar(int a) {
      switch (a) {
         case 1:
            break;
         case 2:
            break;
      }
   }
}
public class Foo {
   void bar(int a) {
      switch (a) {
         case 1:  // do something
            break;
         case 2:
            break;
         default:  // the default case should be last, by convention
            break;
      }
   }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis