mardi 28 décembre 2021

How do you handle async initialization of an object?

Let's say I have an object Foo which requires some asynchronous work, bar(), to be done before it is ready to be used. It feels like each solution I try, I run into an anti-pattern.

Solutions considered:

  • Keep an initialized variable in Foo. Call bar() in Foo's constructor. When bar() completes, set initialized = true. My issue with this approach is that it introduces uninitialized and initialized states into the object, which in my understanding should be avoided.

  • Setup Foo in a parent and inject the data in via arguments. My problem with this approach is that it just pushes the issue farther up the stack; if this is done, now some other class is responsible for doing Foo's initial work.

What is common practice in a situation like this? Thanks!

Aucun commentaire:

Enregistrer un commentaire