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