Default label should be last in a switch

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

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;
      }
   }
}