[SalesForce] Where is SobjectType.newSObject useful

I was going through a document at the SObjectType class where there was a method named – newSObject(recordTypeId, loadDefaults). I see that using this method one can create a new Sobject with default values of
custom fields assigned. But I am started to think that what is the difference between below two ways of creating a object say Account object:

Suppose there is a custom field on account named class__c with a default value as "Fresh".

1st approach: this will create a new account- Acme, with a default value of class__c as "Fresh":

Account acc = new Account(Name='Acme);
Insert acc;

2nd approach: this is from the documentation:

// Create an account with predefined default values
Account acct = (Account)Account.sObjectType.newSObject(null, true);
// Provide a value for Name
acct.Name = 'Acme';
// Insert new account
insert acct;

I am a bit confused here that why would we use Account.sObjectType.newSObject(null, true); to populate the default value of custom field when the default value of field
gets populated automatically when a new account is created. My question is why do we need to explicitly do Account.sObjectType.newSObject(null, true)? What is a difference between
1st way and 2nd way. I am sure I am missing some concept here:)

Best Answer

If you want to write a utility that creates records, this function is absolutely necessary in order to be generic at all. Sure, you could also use Type.forName, but that doesn't take nearly as good advantage of strict typing.

Simply contrast these test utility styles and imagine which will balloon massively each time you want to support new object types:

public static List<SObject> createRecords(SObjectType sObjectType, Integer count)
{
    List<SObject> records = new List<SObject>();
    for (Integer i = 0; i < count; i++)
        records.add(sObjectType.newSObject());
    return records;
}

public static List<Account> createAccounts(Integer count)
{
    List<Account> records = new List<Account>();
    for (Integer i = 0; i < count; i++)
        records.add(new Account());
    return records;
}

Also, note that the optional parameters allow you to instantiate the object with its default values, a useful feature that you would not be able to accomplish using your first approach (concrete type instantiation). This functionality is quite useful in writing tests that perform consistently as expected.

Related Topic