Skip to main content
added 12 characters in body
Source Link
Brian Agnew
  • 4.7k
  • 27
  • 20

I would normally just check for intiialisation and throw (say) an IllegalStateException if you try and use it whilst not initialised.

However, if you want to be compile-time safe (and that seemsis laudable and preferable), why not treat the initialisation as a factory method returning a constructed and initialised object e.g.

ComponentBuilder builder = new ComponentBuilder();
Component forClients = builder.initialise(); // the 'Component' is what you give your clients

and so you control the objects creation and lifecycle, and your clients get the Component as a result of your initialisation. It's effectively a lazy instantiation.

I would normally just check for intiialisation and throw (say) an IllegalStateException if you try and use it whilst not initialised.

However, if you want to be compile-time safe (and that seems laudable), why not treat the initialisation as a factory method returning a constructed and initialised object e.g.

ComponentBuilder builder = new ComponentBuilder();
Component forClients = builder.initialise(); // the 'Component' is what you give your clients

and so you control the objects creation and lifecycle, and your clients get the Component as a result of your initialisation. It's effectively a lazy instantiation.

I would normally just check for intiialisation and throw (say) an IllegalStateException if you try and use it whilst not initialised.

However, if you want to be compile-time safe (and that is laudable and preferable), why not treat the initialisation as a factory method returning a constructed and initialised object e.g.

ComponentBuilder builder = new ComponentBuilder();
Component forClients = builder.initialise(); // the 'Component' is what you give your clients

and so you control the objects creation and lifecycle, and your clients get the Component as a result of your initialisation. It's effectively a lazy instantiation.

Source Link
Brian Agnew
  • 4.7k
  • 27
  • 20

I would normally just check for intiialisation and throw (say) an IllegalStateException if you try and use it whilst not initialised.

However, if you want to be compile-time safe (and that seems laudable), why not treat the initialisation as a factory method returning a constructed and initialised object e.g.

ComponentBuilder builder = new ComponentBuilder();
Component forClients = builder.initialise(); // the 'Component' is what you give your clients

and so you control the objects creation and lifecycle, and your clients get the Component as a result of your initialisation. It's effectively a lazy instantiation.