When I have a class A
in a module amod
as follows
// module amod
type AConfig = {
x: number;
// ...
};
class A {
constructor(public config: AConfig) {}
// ...
}
export {A, type AConfig}
and want to decare a class B
in a separate module bmod
that makes use of A
, what would be the better approach?
Approach 1:
// module bmod
import {A, type AConfig} from 'amod';
class B {
protected _a: A;
constructor(aConfig: AConfig) {
this._a = new A(aConfig);
}
}
Approach 2:
// module bmod
import {type A} from 'amod';
class B {
protected _a: A;
constructor(a: A) {
this._a = a;
}
}
So far, I always went with approach 2 because it seemed to me as if it only had advantages. For example, I can give the same instance a
to multiple instances of B
, or use decorators.
However, I now understood that there is also at least one big disadvantage of approach 2: Any module cmod
that wants to make use of B
must not only depend on bmod
but also on amod
(to create the instance of A
passed to the B
constructor), which can easily introduce subtle bugs due to different versions of amod
between bmod
and cmod
and thus requires careful version management. That would not be necessary for approach 1.
Is there a common design for this problem, or at least a best practice?
amod
aConfig
besides just creating anA
, because otherwise why wouldn't it just accept theA
?