[SalesForce] Omission or inclusion of curly braces in for loop logic – what is the difference

I see differences in use of curly braces in for loops quite frequently.

One style is to be very explicit with the curly braces at the end of a for/if statement. For example:

for (Opportunity opp : opportunityList){

Another style I see is that there is an omission of this curly brace at the end of a for/if statement. For example:

for (Opportunity opp : opportunityList)

So as I understand it, the difference is that the former is explicit and the latter is implicit and usage is based on personal preferance (the latter being more concise, but the former maybe being force of habit).

Is that correct? Or is there a difference between the two in terms of performance?

Thanks,

Best Answer

If the number of statements following the for/if is single you don't have to use curly braces.

But if the number of statements is more than one, then you need to use curly braces. If you don't use curly brace in this scenario, then the first line will execute only in the context of for/if, other lines will execute at all times.

Example:

if(condition){ // Not required
    statement1;
} // Not required

if(condition) { // Required
    statement1;
    statement2;
} // Required

if(condition)
statement1; // This will execute if condition satisfies
statement2; // This will execute anyway

for(iteration condition){ // Not required
    statement1;
} // Not required

for(iteration condition) { // Required
    statement1;
    statement2;
} // Required

for(iteration condition)
statement1; // This will execute for n times
statement2; // This will execute only once

Hope it helps to understand.

Related Topic