vendredi 1 mai 2020

What is the proper approach of initializing an object (Factory, Init, DI), design pattern?

What is the best way to handle the next case: We have a class, which is injecting some other class in a constructor. Constructor besides this injection has some other parameters.

class A
{
    constructor(B b, int x, int y);
}

Just because constructor has non-injectable values, which are different each time, we cannot rely on IOC no more and deal with them manually.

There's 2 ways: 1) Implement method Init(int x, int y), which will initialize our object with non-injectable properties and remove them from constructor, so IOC framework will handle it automatically 2) Create a factory, which will have a creator method for this object, and this method will accept x and y

1)

class A
{
    constructor(B b);
    init(int x, int y);
}

2)

class A
{
    constructor(B b, int x, int y);
}

class AFactory
{
   constructor(B b);
   createA(int x, int y)
   { return new A(b, x, y); }
}

Drawbacks of 1st way - we need to declare all initializable variables as nullable, because initialization is not guaranteed and we need to keep in mind to call init method.

Drawbacks of 2nd way - if object will have a lot of injections - we need to inject them to factory c-tor and pass them to a c-tor of creatable object

The most safe IMO is 2nd approach, as it is safer, than the 1st in terms of initialization guarantees, but it's not good enough

Maybe there's another way of doing it, or improving ways described above?

This question could be related in general to all languages and frameworks, but FYI I'm using plain typescript + inversify

Aucun commentaire:

Enregistrer un commentaire