Suppose I have a constructor that performs an expensive IO operation that takes a noticeable amount of time. I don't like it for a few reasons (first of all, it's simply wrong, but there are practical considerations too)
What should I do?
I see two options
- Extract the expensive operation into a separate method. That method may return some async wrapper (
CompletableFuture
,Mono
). The clients that call the constructor should be updated to include the new method call after constructor calls (in case they relied on a fully initialized state)
MyClass myClass = MyClass();
CompletableFuture<MyClass /* or some specific component that is expensively initialized*/> = myClass.initAsync();
- Remove the constructor from the public API altogether, replace it with a factory method returning an async wrapper. I would have to identify all the places the "expensive" state is used and move that logic to the callbacks passed to the async wrapper. It feels more right
MyClass.createAsync().thenAccept(/* consumer code */)`)
What do you think?
SwingUtilities.invokeLater(..)
). But I guess it's a different story