As discussed last time, usually a proper constructor is the best way to create a new instance. But what do you do if a constructor doesn’t fit your needs?

This might happen if you need to do something asynchronous during creation - and C# doesn’t have asynchronous constructors.

In C#, your declaration might look like this:

public class ImportOperation
{
    public static async ImportOperation Create(ServiceClient client) { 
        // ... elided ...
    }

}

with this consumption:

var operation = await ImportOperation.Create(client);

In Go, which doesn’t have constructors at all (and where asynchrony isn’t a part of method signatures), you end up with a very similar result:

operation := NewImportOperation(client)

Factories have other options as well. For example, they can offer instance pooling, allowing for reuse of instances.

Remember, the goal here isn’t to make life difficult for the developer consuming your operation.

Quite the opposite, in fact - the goal here is to make your operation as simple to use as possible.

Requiring the user to call Initialize() after construction is error prone; better to structure things in such a way that they don’t have to remember to call it.

After all, that developer probably has a (literal!) thousand other things to remember; making their life easier is well worth the effort.

So what do you do if you can’t avoid the Initialize() call? Say, if construction and initialization of our operation need to happen at different times?
(The obvious answer is to restructure your code so that you don’t need to do these at different times, but let’s put that to one side for now.)

Comments

blog comments powered by Disqus
Next Post
Browsers and WSL  31 Mar 2024
Prior Post
Using Constructors  27 Feb 2023
Related Posts
Browsers and WSL  31 Mar 2024
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Archives
March 2023
2023