Default label should be last in a switch

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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

PREVIEWING: rtrieu/product-analytics-ui-changes