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

763    Asked by Yashraj in Salesforce , Asked on Aug 8, 2021

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?



Answered by Mohit Choudhary

 Your #2 actually addresses most parts of it in instantiate vs initialize

You should initialize a property during its declaration only if you know that it does not throw exceptions. Having it in the constructor will let you address it.

From a different perspective, there's none. Sometimes choosing one over the other provides more readability.

It is a very good explanation available on Java documentation like:

As you have seen, you can often provide an initial value for a field in its declaration.

This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.



Your Answer

Interviews

Parent Categories