Home SalesforceApex Object Initializer in Salesforce Apex

Object Initializer in Salesforce Apex

by Dhanik Lal Sahni
Object Initializer in Apex

C#/Java Developers always try to implement similar code practices in Salesforce Apex. One of the important code features is the object initializer which can be used to initialize class properties while creating and initializing objects. Salesforce supports object initializer only for sObject and not for custom classes. This post will show how we can implement Object Initializer in Salesforce Apex.

Object Initializer is a way to assign properties values at the time of object creation. It does not require constructor call to assign property values.

Why we need object initializer in Salesforce:

We create a lot of fields or properties in the Apex class. These properties add business functionality in that class. Before using any class method we have to assign properties like the below or we have to pass all required properties as method parameters.

AddressService addService=new addService();
zip.ZipCode='10011';
zip.Address1='47 W 13th St';
zip.Address2='';
zip.State='NY';
zip.City='New York';
zip.verifyAddress();

This code has no issue but the assignment is done in multiple lines so execution is also multiple times. There should be a way to assign all class properties using a single-line statement.

Salesforce does not support object initializers for custom classes. This post will give an alternate way to create a similar kind of concept. Execution will be still in multiple lines as we will assign values one by one in the class constructor. The benefit will be single line assignment will be done while object creation so it will be cleaner and maintainable code.

For better code practice also we should use a maximum of 3 parameters. If we have more parameters, we will add more functionality in a single method. So it will be better to use fewer parameters with smaller methods. This will help in maintainable code as well. Let us see how we can use the object Initializer concept in apex.

1. sObject Initializer

Salesforce Apex supports sObject initializer and we can initialize properties while object creation. Let us take, we want to post one feed item record then we can use the below code which is using an object initializer

FeedItem objPost=new FeedItem(
    IsRichText=true,
    ParentId = '0012v00003JMBTqAAP',
    Body = 'Hello there from <b>SalesforceCodex.com</b>'
);
insert objPost;

Similarly, we can use an object initializer for a custom object as well. In the below example, I am using the custom object CodeCoverage__c to initialize field values.

CodeCoverage__c code=new CodeCoverage__c(
    ApexClassOrTriggerName__c='0012v00003JMBTqAAP',
    PercentCovered__c=10
);
insert code;

2. Apex Class Initializer

We create classes to add a custom solution for a business requirement that we can not achieve using any standard features. We keep adding classes to accomplish the custom requirement. As a best practice, we should use OOPs (Object Oriented Principle) concept in the apex code. When we implement the OOPs concept we have to instantiate classes to use it. In Salesforce apex, we have a limitation that we can not use an object initializer to instantiate it.

Let us see how we can implement object initializer behavior. We have below apex class HttpCall.

public class HTTPCall {
    public string endPointUrl{get;set;}
    public string method{get;set;}
    public string userName{get;set;}
    public string password{get;set;}
    public integer timeOutDuration{get;set;}
    public string body{get;set;}
}

We will use the below code to instantiate this class to implement third-party integration.

HTTPCall call=new HttpCall(
    EndPoint='https://api.google.com/voice/search',
    Method='Get'
);

When we run the above code it will throw an error

Invalid constructor syntax, name=value pairs can only be used for SObjects: HTTPCall

This error shows that we can not initialize objects similar to sObject initializer. Now let us solve this error by creating a constructor.

Create Constructor

We can create a constructor to initialize object properties. We can add many parameters to instantiate each property. We can use constructor overloading as well to instantiate a different set of properties.

public class HTTPCall {
    public string endPointUrl{get;set;}
    public string method{get;set;}
    public string userName{get;set;}
    public string password{get;set;}
    public integer timeOutDuration{get;set;}
    public string body{get;set;}
    
    public HTTPCall(string endPoint,string method, string body)
    {
        endPointUrl=endPoint;
        method=method;
    }
    public HTTPCall(string endPoint,string method,string userName, string password, string body)
    {
        endPointUrl=endPoint;
        method=method;
    }
}

We can now instantiate objects using the below code.

//First Constructor Called
HTTPCall call=new HttpCall('https://api.google.com/voice/search','Get','{"customers":{"firstName": "Joe”,"lastName": “Bloggs”}}');


//Second Constructor Called
HTTPCall call=new HttpCall('https://api.google.com/voice/search','Get','userName','Password','{"customers":{"firstName": "Joe”,"lastName": “Bloggs”}}');

The code logic is correct and we will not get any issues while running. We will find the issue when we run Apex PMD for code analysis. We will get the below warning for the second constructor as a maximum of 3 parameters is good for best code practice.

Avoid long parameter lists (rule: Design-ExcessiveParameterList)

Let us resolve this warning using the second approach of creating a constructor.

Constructor with Map parameters

In this approach, we will use the Map object to create a collection and pass it to the constructor. We can pass primitive, derived, or object data types as well.

public class HTTPCall {
    public string endPointUrl{get;set;}
    public string method{get;set;}
    public string userName{get;set;}
    public string password{get;set;}
    public integer timeOutDuration{get;set;}
    public string body{get;set;}
    
    public HTTPCall(string endPoint,string method, string body)
    {
        endPointUrl=endPoint;
        method=method;
    }

    public HTTPCall(Map<String, string> initMap)
    {
        endPointUrl = initMap.get('endPoint');
        method = initMap.get('method');
        userName = initMap.get('userName');
        password = initMap.get('password');
        body = initMap.get('body');
    }
}

We will call the second constructor like below to initialize properties.

Map<String, String> initMap=new Map<String, String>{
    	'endPointUrl' => 'https://api.google.com/voice/search', 
        'method' => 'GET', 
        'userName' => 'username',
        'password'=>'password',
        'body'=>'{"customers":{"firstName": "Joe”,"lastName": “Bloggs”}}'
};
HTTPCall call=new HTTPCall(initMap);

This map initializer can be used in method as well to pass multiple parameters.

References

Does Apex have an equivalent to the C# object initializer?

Similar Posts:

Enhance Apex Performance with Platform Caching

Apex Trigger Code Optimization

Optimize Code by Disabling Debug Mode

Optimizing Salesforce Apex Code

Optimizing Loop in Apex Code

Need to discuss the topic

If you want to discuss further on this topic or any other Salesforce topic, please ping me on my LinkedIn profile.

You may also like

Leave a Comment