Apex Switch Explained!

Good news Dev folks! Apex switch statement released in Winter 18 release.

No more hastle of nested or a ladder of If-else blocks it can be simplified with help of new Switch statements.

Salesforce has delivered one more from IdeaExchange Add "Switch" or "Case" Statement to Apex

Lets take example of finding Quarter of the year using Switch

Syntax

String quarter;

switch on System.today().month() {
    when 1, 2, 3 {		// when block 1
        quarter = 'Q1';
    }	
    when 4, 5, 6 {		// when block 2
        quarter = 'Q2';
    }
    when 7, 8, 9 {		// when block 3
        quarter = 'Q3';
    }
    when else {		  // when else block, optional
        quarter = 'Q4';
    }
}

Easy right? Make use of the new feature.

Here are few points for consideration between Switch statement vs If-else?

  • Switch is more compact and readable
  • Switch is very easy to use when there are multiple choices which helps avoids nested if-else blocks
  • Unlike If-else, Switch statement jumps to directly to value rather executing every statement in If-else until condition met true.
  • If-else can have range of values as expression but Switch doesnt do that

NOTE: This feature was in Developer preview

For more info you can refer salesforce release doc here