dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
628 stars 172 forks source link

proposal: `avoid_sleep` #4808

Open julemand101 opened 8 months ago

julemand101 commented 8 months ago

Description

AVOID calling sleep function from dart:io.

The function should be used with care, as no asynchronous operations can be processed in a isolate while it is blocked in a sleep call.

Kind

Guard against surprised program execution where developer gets confused why no async events are being executed while sleeping.

Bad Examples

import 'dart:io';

void main() {
  sleep(const Duration(seconds: 5));
}

Good Examples

import 'dart:io';

void main() async {
  await Future<void>.delayed(const Duration(seconds: 5));
}

Discussion

I have seen recently, and in the past, a few people getting confused about sleep and misunderstood the consequences of using it (or did not read the documentation). My guess is developers knows the word sleep and thinks that is the way to do sleeping in a function. But then gets surprised when no other code in the isolate gets executed while sleeping.

Most recently example: https://stackoverflow.com/questions/77533267/async-would-not-run-async-in-dart

I do think sleep are very rarely useful and will in most cases be the wrong thing to actually use when the developer wants to insert a delay in code execution.

My suggested lint could be compared to avoid_print which is also about preventing calling a method from the Dart SDK.

Discussion checklist

lrhn commented 8 months ago

IMO, this seems far too specific. There are lots of functions that you should use with care (don't call exit if you don't mean it!), and having a lint per function doesn't really scale. Doing sleep isn't much worse than doing calling a Sync function on File, they both block the isolate until they return. The issue with sleep is not what it does, but that people misread it.

If there is a list of "dangerous" APIs that you shouldn't use, or some common kind of functions that you should be aware of, it might make sense to have a shared lint for them.