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 instantiate Bar (for instance,Bar b = new Bar();
) properly handle it?