Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Thursday, May 29
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Apex»Object Initializer in Salesforce Apex

    Object Initializer in Salesforce Apex

    Dhanik Lal SahniBy Dhanik Lal SahniDecember 10, 2022Updated:January 12, 2025No Comments5 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Object Initializer in Apex
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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.

    apex apex code analysis apex map apex per apex performance apex pmd architecture best code practice code optimization constuctor overloading map in apex method overloading object initializer salesforce salesforce apex sObject initializer
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleGenerate Topic Followers List
    Next Article Secure Apex Code with User Mode Operation
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni4 Mins Read

    How to Build a Generic Modal Window in Lightning Web Component

    May 26, 2025
    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) file upload (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (30) Lightning web component (62) lwc (51) named credential (8) news (4) optimize apex code (4) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (141) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) file upload (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (30) Lightning web component (62) lwc (51) named credential (8) news (4) optimize apex code (4) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (141) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.