Any custom lint for disposing classes?

There’s no official lint that checks that .dispose() is called for classes that define or inherit a dispose() method. I bet it’s because:

  1. The lint could be quite slow
  2. There’s no fool-proof way to implement it (sometimes, you don’t need to run dispose(), or you call it from a different place than where you instantiate the class)

But I still think it could find some leaks, and now with sdk/pkg/analysis_server_plugin/doc/writing_rules.md at main · dart-lang/sdk · GitHub (custom rules), it’s in the realm of possible to implement it.

Now I wonder if anyone has looked into this. I’m hardly the first person with this idea.

For posterity, here’s my thinking of how it would work.

  • Find a class Foo that has a void dispose() or a Future<void> dispose() method.
  • Find libraries (Dart files) in which Foo is instantiated (... = Foo();).
  • Ensure that there is at least one place where .dispose() is called on an instance of Foo.

This has obvious problems (what if I pass Foo.new to somewhere? what if I call dispose() in one code path but not the other?). But even in this form, I think it has a potential to find some bugs.

Are you familiar with the leak_tracker package? It lets your write tests to verify your objects are properly disposed: leak_tracker/doc/leak_tracking/OVERVIEW.md at main · dart-lang/leak_tracker · GitHub

Thanks for mentioning it! I’ve been seeing leak_tracker in my pubspec.locks for a while but never got around reading up on it. I’ll try it now.

1 Like

Ok, so I’m reporting back. leak_tracker is great and way more powerful than a lint could ever be. The DevExp is not great (or I’m too dumb to understand it) but with a little bit of tweaking, I was able to find several memory leaks in a relatively small app.

Thanks again, Loic, for bringing it up!

FWIW, I think leak_tracker probably deserves more hype.

1 Like