Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    • Building a Dynamic Tree Grid in Lightning Web Component
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Wednesday, July 30
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    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 Sahni6 Mins Read

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 2025
    By Dhanik Lal Sahni14 Mins Read

    The Ultimate Guide to Apex Order of Execution for Developers

    July 20, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 Salesforce Developer Blog by SalesforceBen.com
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (149) salesforce apex (52) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) 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

    MailChimp

    Expert Salesforce Developer and Architect
    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 10 Salesforce CRM Trends to Watch in 2025 July 18, 2025
    • Discover the Top 10 Salesforce AppExchange Apps to Boost Productivity July 10, 2025
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • 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
    Archives
    Categories
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (149) salesforce apex (52) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) 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

    banner
    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.