Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

What is the difference between initializing a class property inline vs constructor

Asked by Yash Raj Aug 8, 2021 1.3K views 1 answer
Share

About this question

There is a similar question: What is the difference between initializing properties in shorthand vs constructor? on this forum, but I wanted to get more descriptive explanation on the "difference" (pros/cons and obvious use cases) between:

Property is initialized inline

public with sharing class Bar { private Foo fooProperty = new Foo(); public Bar() {} }

Property is initialized in constructor

public with sharing class Bar { private Foo fooProperty; public Bar() { fooProperty = new Foo(); } }

I hope this this question is not too broad, taking into consideration the questions below:


What are the main differences between these approaches and when should I prefer one over the other? I see one difference - place where = new Foo(); is placed in the code.


Given a scenario when the new Foo() statement throws an exception, how should the client that instantiates Bar (for instance, Bar b = new Bar();) properly handle it?



Your answer

1 Answer

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.