banned_usage
Flags uses of a member you ban — one method, getter or constructor of a type rather than the whole type. The common need is DateTime.now() and Random() in code that should take an injected clock or seed.
DateTime.now() is a hidden input: a type that calls it cannot be tested at a chosen moment. Banning it inside the domain layer while leaving it available in the composition root puts the constraint where it belongs — the code that decides when may know the time; the code that decides what may not.
This rule is in no preset and reports nothing until you add banned:. Every example below shows the configuration that produces it.
many_lints: rules: banned_usage: banned: - deny: ['DateTime.now', 'Random.new'] in: ['lib/domain/**'] message: 'Inject a clock or seed so this stays testable.'rules: banned_usage: banned: - deny: ['DateTime.now', 'Random.new'] in: ['lib/domain/**'] message: 'Inject a clock or seed so this stays testable.'Members are written Type.member, matched on the type that declares the member. The unnamed constructor is spelled new. A member of an extension, static or instance, is written Extension.member: deny: ['Doubling.twice'] reports 3.twice for extension Doubling on int.
What counts as a use
Section titled “What counts as a use”Every way of referring to a banned member is reported once:
- calls and constructor invocations:
DateTime.now(),Random(),Random.new() - tear-offs:
DateTime.nowandRandom.newpassed as a value,Box<int>.of - reads and writes of a getter, setter or field:
Clock.current,Clock.instance = clock - dot shorthands:
.now(),.new(),.current - import prefixes:
core.DateTime.now(),math.Random.new - unqualified uses inside the declaring class:
now()in a static method ofClock - constructor redirection:
super.system(),this.system(),factory Clock.fixed() = Clock.system;
A doc comment reference such as [DateTime.now] and a show/hide combinator name the member without using it, so they are not reported. A local function, local variable or parameter that shares the member’s name is not the member and is never reported.
Examples
Section titled “Examples”Force an injected clock
Section titled “Force an injected clock”- deny: ['DateTime.now'] in: ['lib/domain/**'] message: 'Inject a clock so this stays testable.'// Don't — in lib/domain/session.dartclass Session { const Session(this.expiresAt);
final DateTime expiresAt;
// LINT: cannot be tested without waiting for real time to pass. bool get isExpired => DateTime.now().isAfter(expiresAt);}// Do — in lib/domain/session.dartabstract class Clock { DateTime now();}
class Session { const Session({required this.expiresAt, required Clock clock}) : _clock = clock;
final DateTime expiresAt; final Clock _clock;
bool get isExpired => _clock.now().isAfter(expiresAt);}Catch tear-offs and dot shorthands
Section titled “Catch tear-offs and dot shorthands”Passing DateTime.now as a value hands out the same hidden input as calling
it, and .now() is the same constructor under a shorthand. Both are reported:
- deny: ['DateTime.now'] message: 'Inject a clock so this stays testable.'// Don'tclass Session { Session({DateTime Function()? now}) : _now = now ?? DateTime.now; // LINT
final DateTime Function() _now;}
DateTime startedAt() => .now(); // LINT// Doabstract class Clock { DateTime now();}
class Session { Session({required Clock clock}) : _clock = clock;
final Clock _clock;}Ban the unnamed constructor, keep the named one
Section titled “Ban the unnamed constructor, keep the named one”Type.new names the unnamed constructor, so Random() is reported while
Random.secure() is left alone:
- deny: ['Random.new'] message: 'Pass a seeded Random so failures reproduce.'// Don'tint roll() => Random().nextInt(6); // LINT
// Doint roll(Random random) => random.nextInt(6);Ban a member declared on a supertype
Section titled “Ban a member declared on a supertype”The declaring type is what matches, so an Iterable.first entry also catches a
List receiver — a subclass cannot slip past:
- deny: ['Iterable.first'] message: 'first throws on empty; use firstOrNull and handle the null.'// Don'tint? firstScore(List<int> scores) => scores.first; // LINT
// Doint? firstScore(List<int> scores) => scores.firstOrNull;Writing List.first instead would report nothing here: first is declared on
Iterable, not on List.
Only instance members reach subtypes this way. Constructors and static members
are not inherited, so deny: ['Random.new', 'DateTime.now'] does not report
FixedRandom(4) for class FixedRandom implements Random, or a subclass’s own
FakeTime.now() constructor.
Ban a member on every type
Section titled “Ban a member on every type”A bare member name, with no Type. prefix, bans it wherever it appears:
- deny: ['toString'] in: ['lib/api/**'] message: 'Serialize through toJson; toString is for debugging.'// Don't — in lib/api/payload.dartString encode(Object value) => value.toString(); // LINT
// DoString encode(Map<String, Object?> json) => jsonEncode(json);Prefer the qualified form unless you really mean every type — deny: ['now']
catches DateTime.now() and any other member named now.
Ban a top-level function or variable
Section titled “Ban a top-level function or variable”A top-level declaration has no type to qualify it. Write it with its library,
uri#name, using the same # separator as
avoid_banned_types:
- deny: ['package:my_app/core/clock.dart#systemClock'] in: ['lib/domain/**'] message: 'Take the clock as a parameter.'// Don't — in lib/domain/order.dartOrder newOrder() => Order(at: systemClock.now()); // LINT
// DoOrder newOrder(Clock clock) => Order(at: clock.now());The library is the one that declares the name, not the one you import, so
an import prefix or a re-exporting barrel does not hide a use. A member named
systemClock on some type, or a systemClock declared in another library, is
not matched. A bare deny: ['systemClock'] still works, but it also bans every
member with that name.
The same prefix pins a member to the library declaring its type:
dart:core#DateTime.now, package:my_app/core/clock.dart#Clock.now. Use it
when two packages declare a type with the same name.
Allow a member in one file only
Section titled “Allow a member in one file only”except: lifts one entry in the paths it names, using the same globs as in:.
The other entries keep applying there:
many_lints: rules: banned_usage: banned: - deny: ['Uuid.new'] in: ['lib/**'] except: ['lib/core/ids/uuid_provider.dart'] message: 'Read ids from the injected id source.' - deny: ['package:my_app/core/clock.dart#systemClock'] in: ['lib/**'] except: ['lib/core/clock.dart', 'lib/main.dart'] message: 'Read the time from the injected clock.'rules: banned_usage: banned: - deny: ['Uuid.new'] in: ['lib/**'] except: ['lib/core/ids/uuid_provider.dart'] message: 'Read ids from the injected id source.' - deny: ['package:my_app/core/clock.dart#systemClock'] in: ['lib/**'] except: ['lib/core/clock.dart', 'lib/main.dart'] message: 'Read the time from the injected clock.'lib/core/ids/uuid_provider.dart may construct a Uuid, but it still may not
read systemClock. lib/main.dart may read systemClock and may not
construct a Uuid. An entry with except: and no in: applies everywhere
except the named paths.
Lift every entry in one file
Section titled “Lift every entry in one file”exclude: (available on every rule) skips paths for the whole rule:
many_lints: rules: banned_usage: exclude: ['lib/src/cli/output/**'] banned: - deny: ['print', 'Stdout.write', 'Stdout.writeln', 'Stdout.add'] in: ['lib/**'] message: 'Return the value and let the renderer emit it.'rules: banned_usage: exclude: ['lib/src/cli/output/**'] banned: - deny: ['print', 'Stdout.write', 'Stdout.writeln', 'Stdout.add'] in: ['lib/**'] message: 'Return the value and let the renderer emit it.'Writing to stdout is now reported everywhere under lib/ except the one
renderer that owns the terminal. Every other entry of the rule is lifted there
too, so prefer except: on the entry when a file needs one exception.
Options
Section titled “Options”| Option | Type | Default | Description |
|---|---|---|---|
banned |
list of entries | [] |
The entries to enforce. With none, the rule reports nothing |
Per entry:
| Key | Type | Required | Description |
|---|---|---|---|
deny |
string or list | one of deny / deny_pattern |
Members banned by exact match, written Type.member, as a bare member, or with the declaring library: uri#name, uri#Type.member |
deny_pattern |
string or list | one of deny / deny_pattern |
Regular expressions, anchored to the whole value and tried against both Type.member and the bare member |
in |
list of globs | no | Paths, relative to the package root, where the entry applies. Omit to apply everywhere |
except |
list of globs | no | Paths, relative to the package root, where the entry does not apply, even inside in. Lifts this entry only |
message |
string | no | A project-specific explanation appended to the diagnostic |
Known limitations
Section titled “Known limitations”Write the declaring type. Iterable.first catches a List receiver, but List.first catches nothing — the member is declared once, on Iterable. When an entry unexpectedly reports nothing, this is usually why.
A pattern is tested against both spellings. deny_pattern is tried against the qualified Type.member and against the bare member, so DateTime\.now and now both report DateTime.now() — and an unanchored-looking pattern like .* bans every member it reaches. It is not tried against the uri#name spelling: write library-qualified entries under deny.
Uses, not declarations. The rule reports where a member is used. Declaring a method named now is avoid_banned_names’s job.
An implicit super constructor call is not reported. A subclass constructor with no initializer list calls the superclass’s unnamed constructor without naming it, so class SeededRandom extends Random { SeededRandom(); } is not reported for Random.new. Write : super() and it is.
Globs have no negation. in: and except: support *, ** and ? but no ! or {a,b} alternatives. List each path instead.
A malformed entry is skipped silently. An invalid regular expression costs you that pattern and nothing else — a plugin cannot report problems against a YAML file.
Related rules
Section titled “Related rules”avoid_banned_annotations— Ban specific annotations, optionally scoped by directory.avoid_banned_exports— Ban re-exports of specific libraries, optionally scoped by directory.avoid_banned_imports— Ban imports of specific libraries, optionally scoped by directory.avoid_banned_names— Ban specific identifiers from being used as declaration names.