mardi 31 mai 2022

Is it generally better to use an async static initializer instead of a public constructor? [closed]

In C#, as well as in other OO languages, calling a class's constructor directly (via new) has historically been the canonical method by which one instantiates a new instance...e.g.,

var emp = new Employee(<parameters/dependencies/etc.>);
// do something with emp:

Despite all that has been written about "new is glue" and the avoidance of tight coupling, I still see this pattern a lot. In my own code, I've started making my constructors private and replacing constructor calls with static initializers. e.g.,

public class Employee
{
    private Employee(<parameters/dependencies/etc.>)
    {
        // do something with inputs:
    }

    public async Task<Employee> CreateInstanceAsync(<parameters/dependencies/etc.>)
    {
        var emp = new Employee(<parameters/dependencies/etc.>);
        // asynchronous initialization logic goes here
        return emp;
    }
}

To me, it seems like a no-brainer. Static initializers have the following advantages over direct constructor calls:

  • They allow for asynchronous initialization logic - which is essential if your class needs to (for example) retrieve configuration settings from an Azure Key Vault or set up a DB connection before being used.
  • They make it easier to adopt the Factory pattern.
  • By constraining the manner in which a class may be instantiated, they give a user a guarantee that the newly-created object will be ready-to-use without needing additional initialization calls.

The only disadvantage I see is if you are using certain packages or patterns which require the existence of a public parameterless constructor (although there are ways to work around this).

What are your thoughts? Should this manner of instantiating class objects be the new standard? Should we keep constructors hidden from the user? Or are there legitimate reasons why one would continue to use public constructors and the old-fashioned new pattern today?

Aucun commentaire:

Enregistrer un commentaire