0

Following Hevery's advice to inject collaborators into constructor rather than new'ing things within constructor body, how gracefully do this when a collaborator needs a back reference to its owner, without using an evil 'init' method (another violation of Hevery's best practices for testable code).

E.g.

    export class Model {
    constructor( history ) {
      this._history = history; // But history needs to know Model too
      history.model = this;    // Is it just as simple as this? Feels awkward
      ...
    }
    ...
   }

vs.

    export class Model {
    constructor() {
      this._history = new History(this); // But new'ing things here reduces testability
      ...
    }
    ...
   }
0

2 Answers 2

0

I think this is a case where you just need to new it up: create the instance in the constructor. If the two things can't exist without each other, and you don't need to utilize polymorphism, then there is no sense in passing the dependency in.

Otherwise you need to break the circular dependency between Model and History.

3

You can inject a factory instead of a instance:

export class Model {
    constructor(HistoryFactory factory) {
      this._history = factory.createHistory(this);
      ...
    }
    ...
}

But I guess Misko would advise you to get rid of the circular dependency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.