Codelyzer: Feature request: disallow explicit calls to lifecycle hooks

Created on 9 Oct 2017  路  8Comments  路  Source: mgechev/codelyzer

Disallow code like

method() {
  this.ngOnDestroy()
}
ngOnDestroy() { /* cleanup code here */}

Instead, we should write something like

cleanup() { /* cleanup code here */}
method() {
  this.cleanup()
}
ngOnDestroy() {
  this.cleanup()
}

As Rob put it, "don't call your own hooks, because one day, you'll be debugging something and you'll be really confused why hooks are firing unexpectedly/out of order/whatever".

Thought it would be a nice addition to codelyzer.

Most helpful comment

I like this proposal. Lets implement it.

All 8 comments

I like this proposal. Lets implement it.

Btw, this is not very trivial to solve in the generic case. We need to check if given object instance implements a lifecycle hook interface and later, it's method is being invoked somewhere.

However, I think a basic check, such as:

  • Find all method invocations in a class.
  • Look for method names reserved by lifecycle hooks.
  • Report a warning if find one.

Seems good enough.

How can I disable this rule for tests?

I can see the benefit for application code, but within specs I actually do want to call lifecycle hooks to test them.

@mgechev I second the question. How can this be disabled just for testing? (Aside for the obvious solution of turning it off in a comment)

There are two options:

  • Comments in the beginning of the file
  • Two tslint config files - one for tests which does not include this rule and another for your app, which includes the rule and extends the original one

@mgechev Just for you to notice, that Angular CLI seems to ignore the linterOptions options setting of tslint. I know that this is also an Angular CLI problem, but the solution of having two tslint config files won't work. Thanks any way.

If there's no issue for this in the Angular CLI repo, it might be worth opening.

angular/angular-cli#11951

Was this page helpful?
0 / 5 - 0 ratings

Related issues

davidanaya picture davidanaya  路  4Comments

rolandjitsu picture rolandjitsu  路  5Comments

fabioemoutinho picture fabioemoutinho  路  5Comments

wKoza picture wKoza  路  6Comments

dev054 picture dev054  路  4Comments