All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.squid.S128.html Maven / Gradle / Ivy

When the execution is not explicitly terminated at the end of a switch case, it continues to execute the statements of the following case. While this is sometimes intentional, it often is a mistake which leads to unexpected behavior.

Noncompliant Code Example

switch (myVariable) {
  case 1:                              
    foo();
    break;
  case 2:  // Both 'doSomething()' and 'doSomethingElse()' will be executed. Is it on purpose ?
    doSomething();
  default:                               
    doSomethingElse();
    break;
}

Compliant Solution

switch (myVariable) {
  case 1:                              
    foo();
    break;
  case 2: 
    doSomething();
    break;
  default:                               
    doSomethingElse();
    break;
}

Exceptions

switch (myVariable) {
  case 0:                                // Empty case used to specify the same behavior for a group of cases.
  case 1:                               
    doSomething();
    break;
  case 2:                                // Use of return statement
    return;
  case 3:                                // Use of throw statement
    throw new IllegalStateException();
  default:                               // For the last case, use of break statement is optional 
    doSomethingElse();
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy