mardi 24 août 2021

Factory concurrent access

when coding factories there's a thing I always do:

final class FooFactory implements FooFactoryInterface 
{
  /**
   * @var array<string=>mixed> - constructor argument names to values
   */
  private array $constructorArguments = [];

  public function withBar(BarInterface $bar): static
  {
    $factory = clone $this;
    $factory->constructorArguments['bar'] = $bar;

    return $factory;
  } 
}

When calling a method of a factory (could be for entity hydration too), I always add it in a new factory to avoid concurrent accesses, always did it by safety, but can the problem even occur ?

Does all clients use the same factory, the object in memory ? I tend to say each request triggers the creation of all objects, which are then destroyed, but i'm not 100% sure the no-cloning version is safe.

Having a void return type would help with code comprehension, in C functions returning the same string they take as arguments are confusing, and if fluent pattern can be avoided I'll take it. Plus, the interface can't enforce affectation has to be done to get the new state of the factory given by the implementing class, which is a problem to me, interface should say it all.

So, to clone or not to clone ? That's the design question.

Aucun commentaire:

Enregistrer un commentaire