function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jason VoightJason Voight 

Object initialization

What is the best practice when initializing objects working with for loop, Is there advantages to Initalze outside the loop, oppose to Inside a loop or setting the Object as a variable and referenceing it inside the loop.A few examples.


 
//Example 1:

Account acc1 = new Account();
for (Integer i = 0, j = 0; i < 10; i++) { 
    acc1 accountToCreate =  createAccount(i);
}



//Example 2:

Account acc2;
for (Integer i = 0, j = 0; i < 10; i++) {
    acc2 accountToCreate =  createAccount(i);
    accsToInsert2.add(acc2);
}


//Example 3:

for (Integer i = 0, j = 0; i < 10; i++) {
    Account acc3 = new Account();
    acc3 accountToCreate =  createAccount();
}

​​​​​​​
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

Can you confirm CreateAccount() is another method with Integer as parameter?

Generally we initialise and assign the values in For loop only. like below.
 
List<Account> acclist= new List<Account>();
For(Integer i = 0, j = 0; i < 10; i++){
Account acc= new Account();
acc.name='sample'+i;
acclist.add(acc);

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
 
Jason VoightJason Voight
Hi Sai.

That is correct it would be calling another method, I'm really looking for an understanding on whats the difference between the 3. If one way of doing it serves a purpose of duplicates or perfromance etc. 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jason,

Generally as the best coding practice we define the variables and initialise them based on the context. Here we need ACC variable only inside the for loop and there is no need to define it above for loop so it need to hold the variable out side of for loop.

Thanks,